Applying an algorithm to a specific region of an image [closed] - matlab

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to apply an algorithm only to a specific region of an image. I tried imfreehand, but not able, at least for me, to do that using this function.
So, is there some way when running my code for the operations to be applied only to some specific region of an image in MATLAB?
Thanks.

Using a mask defined by any of the "imroi" functions - imfreehand and imellipse included, you can use roifilt2 to filter just the roi using a given filter or function.
First, define the area:
imshow(I); %display your image
h = imfreehand; % now pick the region
BW = createmask(h); %makes BW mask
Then, use roifilt2 in one of the following ways -
Define a filter and apply it:
H = fspecial('unsharp');
I2 = roifilt2(H,I,BW);`
Apply a given function to the roi:
I2 = roifilt2(I, BW, 'histeq');
Apply a given function to the roi, specifying parameters:
fh = #(I)(histeq(I,5)); %define function
I2 = roifilt2(I, BW, fh);
The last is equivalent to calling I2 = hist(I,5); but only works on the defined roi.
ETA:
If you want to call multiple functions on the roi, it may be easiest to define your own function, which takes an image input (and optionally, other parameters), applies the appropriate filters/functions to the image, and outputs a final image - you would then call "myfunc" in the same way as "histeq" above.

You can try roipoly.
There is an example on SO here.
Here's an example:
img = imread('peppers.jpg'); % loads the image we want to use
[BW,xi,yi] = roipoly(img); % create a polynomial surrounding region
BW = repmat(uint8(BW),[1,1,3]); % create mask
selIMG = img.*BW; % apply mask to retain roi and set all else to 0
imview(selIMG)
se=strel('disk',3);
erosion=imerode(selIMG,se);
result_image=imsubtract(selIMG,erosion);
imview(result_image)
Edit
On erode: as the matlab doc explains, imerode picks the lowest value from the surrounding pixels (imdilate does the opposite). This means that the original treatment in my answer is inadequate for imerode, it would be better to set pixels outside the selection to max on the colorscale, and I provide an example here on how to do this "manually":
img = imread('peppers.jpg'); % loads the image we want to use
[BW,xi,yi] = roipoly(img); % logical mask which contains pixels of interest
nBW = uint8(~BW); % inverse of logical mask to pick surrounding pixels
surroundingMaxedOut = repmat(255*nBW,[1,1,3]); % set surrounding pixels to max value
nBW = repmat(nBW,[1,1,3]); % make mask with 3 channels to pick surrounding pixels
BW = repmat(uint8(BW),[1,1,3]); % make mask with 3 channels to handle RGB
selIMG = img.*BW; % pick the image region of interest
selIMG = selIMG + surroundingMaxedOut; % final selection with surrounding pixels maxed out
imview(selIMG) % inspect the selection
se=strel('disk',3);
erosion=imerode(selIMG,se); % apply erosion
finalIMG = img.*nBW + BW.*erosion; % insert eroded selection into the original image
imview(finalIMG)
As other answers show, matlab has routines that handle these operations implicitly and are more efficient not least in terms of memory management, however this example provides you with more control so you can see what is happening.

Related

Fill in a region of a binary image which is not completely closed

In MatLab, I have a binary image and I am trying to fill a hole. The problem is that the area is mostly (but not entirely) closed. Is there any existing visual processing functions that can do this? Do I have to write my own algorithm?
Original / Desired
Another separate problem is that I am having trouble detecting thin tail-like structures in a binary image. I need to remove these type of structures without removing the larger body it is attached to. Is there any existing visual processing functions that can do this? Do I have to write my own algorithm?
Original / Desired
In the first example, you can use imclose to perform a dilation followed by an erosion to close those edges. Then you can follow up with imfill to completely fill it in.
img = imread('http://i.stack.imgur.com/Pt3nl.png');
img = img(:,:,1) > 0;
% You can play with the structured element (2nd input) size
closed = imclose(img, strel('disk', 13));
filled = imfill(closed, 'holes');
Similarly, with your second set of images, you can use imopen (erosion followed by dilation) to remove the tail.
img = imread('http://i.stack.imgur.com/yj32n.png');
img = img(:,:,1);
% You can play with the structured element (2nd input) size
% Increase this number if you want to remove the legs and more of the tail
opened = imopen(img, strel('disk', 7));
Update
If you want the centroid of the central opening of the "closed" image above, you can get a mask which is just this opening by subtracting closed from filled.
% Find pixels that were in the filled region but not the closed region
hole = filled - closed;
% Then compute the centroid of this
[r,c] = find(hole);
centroid = [mean(r), mean(c)];

Image segmentation based upon optical features [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have an image with some texture in a region shown in the first image. I want to segment the image based upon this texture. For this I have extracted feature as shown with blue squares (second image). I want to extract the region bound to the rectangular distribution of the features (shown by red dotted line).
Image 1:
Image 2:
Can somebody help me by suggesting some methodology to pursue this problem. Thanks
This looks like it might fit the GraphCut image segmentation framework:
You want to find a binary assignment per-pixel (1 - this pixel belongs to the foreground, 0 - the pixel is part of the background). This assignment should include as many "texture locations" as possible in the foreground, while preserving "smooth boundaries" between foreground and background.
The smoothness requirement prevents your "ideal" assignment to be 1 for the blue dots and zero everywhere else.
Now, how to search for such a binary assignment using Matlab?
Assume you have img of size H-by-W, and you have detected the locations of the texture features and stored these location in a 2-by-n matrix locs.
Setting the per-element cost:
>> bgCost = zeros( H, W );
>> bgCost( [1 H] * (locs-1) + 1 ) = 1000; %// put 1000 penalty for assigning texture dot to foreground
>> fgCost = 10*ones( H, W ); %// assign some positive penalty for assigning non-texture location to FG - prevent an "all foreground" solution.
>> fgCost( [1 H] * (locs-1) + 1 ) = 0;
Optimization:
>> lambda = 5; %// set relative weight between smoothness term and "texture" term
>> gch = GraphCut('open', cat(3, fgCost,bgCost), lambda * [0 1;1 0],
>> [gch BW] = GraphCut('expand', gch ); %//optimization
>> gch = GraphCut('close', gch ); %//cleanup
You should get a nice binary mask in BW
>> figure;imshow( BW, [] );title('binary mask');
There are three parameters you can play with if you are not satisfied with the result BW:
the cost you assign to texture dots in the background (set to 1000 here).
the cost you assign to non-texture pixels in the foreground (set to 10 here).
the relative strength of the smoothness cost lambda.
Try and change these values and see how they influence the resulting mask.
I use this matlab wrapper for GraphCut optimization.

How do I denoise a simple grayscale image

Here is the original image with better vision: we can see a lot of noise around the main skeleton, the circle thing, which I want to remove them, and do not affect the main skeleton. I'm not sure if it called noise
I'm doing it to deblurring a image, and this image is the motion blur kernel which identify the camera motion when the camera capture a image.
ps: this image is the kernel for one case, and what I need is a general method in here. thank you for your help
there is a paper in CVPR2014 named "Separable Kernel for Image Deblurring" which talk about this, I want to extract main skeleton of the image to make the kernel more robust, sorry for the explaination here as my English is not good
and here is the ture grayscale image:
I want it to be like this:
How can I do it using Matlab?
here are some other kernel images:
As #rayryeng well explained, median filtering is the best option to clean noise in the image, which I realized when I had studied about image restoration. However, in your case, what you need to do seems to me not cleaning noise in the image. You want to more likely eliminate the sparks in the image.
Simply I applied single thresholding to your noisy image to eliminate sparks.
Try this:
desIm = imread('http://i.stack.imgur.com/jyYUx.png'); % // Your expected (desired) image
nIm = imread('http://i.stack.imgur.com/pXO0p.png'); % // Your original image
nImgray = rgb2gray(nIm);
T = graythresh(nImgray)*255; % // Thereshold value
S = size(nImgray);
R = zeros(S) + 5; % // Your expected image bluish so I try to close it
G = zeros(S) + 3; % // Your expected image bluish so I try to close it
B = zeros(S) + 20; % // Your expected image bluish so I try to close it
logInd = nImgray > T; % // Logical index of pixel exclude spark component
R(logInd) = nImgray(logInd); % // Get original pixels without sparks
G(logInd) = nImgray(logInd); % // Get original pixels without sparks
B(logInd) = nImgray(logInd); % // Get original pixels without sparks
rgbImage = cat(3, R, G, B); % // Concatenating Red Green Blue channels
figure,
subplot(1, 3, 1)
imshow(nIm); title('Original Image');
subplot(1, 3, 2)
imshow(desIm); title('Desired Image');
subplot(1, 3, 3)
imshow(uint8(rgbImage)); title('Restoration Result');
What I got is:
The only thing I can see that is different between the two images is that there is some quantization noise / error around the perimeter of the object. This resembles salt and pepper noise and the best way to remove that noise is to use median filtering. The median filter basically analyzes local overlapping pixel neighbourhoods in your image, sorts the intensities and chooses the median value as the output for each pixel neighbourhood. Salt and pepper noise corrupts image pixels by randomly selecting pixels and setting their intensities to either black (pepper) or white (salt). By employing the median filter, sorting the intensities puts these noisy pixels at the lower and higher ends and by choosing the median, you would get the best intensity that could have possibly been there.
To do median filtering in MATLAB, use the medfilt2 function. This is assuming you have the Image Processing Toolbox installed. If you don't, then what I am proposing won't work. Assuming that you do have it, you would call it in the following way:
out = medfilt2(im, [M N]);
im would be the image loaded in imread and M and N are the rows and columns of the size of the pixel neighbourhood you want to analyze. By choosing a 7 x 7 pixel neighbourhood (i.e. M = N = 7), and reading your image directly from StackOverflow, this is the result I get:
Compare this image with your original one:
If you also look at your desired output, this more or less mimics what you want.
Also, the code I used was the following... only three lines!
im = rgb2gray(imread('http://i.stack.imgur.com/pXO0p.png'));
out = medfilt2(im, [7 7]);
imshow(out);
The first line I had to convert your image into grayscale because the original image was in fact RGB. I had to use rgb2gray to do that. The second line performs median filtering on your image with a 7 x 7 neighbourhood and the final line shows the image in a separate window with imshow.
Want to implement median filtering yourself?
If you want to get an idea of how to actually write a median filtering algorithm yourself, check out my recent post here. A question poser asked to implement the filtering mechanism without using medfilt2, and I provided an answer.
Matlab Median Filter Code
Hope this helps.
Good luck!

Extract Individual Line Segment Coordinates from Boundary Image - MATLAB

I have a MATLAB script that gives me the boundary lines of an image using bwboundaries().
Now, after plotting that image, I am getting the complete image, formed from various straight line segments.
I would like to get the coordinates or show the individual line segments that form the boundary.
I think the method is called digital straightness of lines, but I want to know how to apply it here in this case.
[B,L,N] = bwboundaries(z,'noholes');
for k=1:length(B),
boundary = B{k};
if(k > N)
figure, plot(boundary(:,2),boundary(:,1),'g','LineWidth',2);
else
figure, plot(boundary(:,2),boundary(:,1),'r','LineWidth',2);
end
end
According to my understanding of your question,my idea is to use bwtraceboundary().
BW = imread('image.png');
imshow(BW,[]);
r = 165; % you can get the r and c for your image using "impixelinfo"
c = 43;
contour = bwtraceboundary(BW,[r c],'W',4,Inf,'counterclockwise');
hold on;
plot(contour(:,2),contour(:,1),'g','LineWidth',2);
x=contour(:,2)'
y=contour(:,2)'
Am I answering your question?
Use regionprops('desired feature') on the labelled image.
To generate a labelled image use
bwlabel(Img) (high memory usage)
or
bw=bwconncomp(Img,conn) (low memory use)
followed by
labelmatrix(bw)
The best way to proceed would probably be to use a Hough Transform to first get an idea of the lines present in the image. You can play around with Hough Transform to extract the end points of the lines.

MATLAB Image Processing - Find Edge and Area of Image

As a preface: this is my first question - I've tried my best to make it as clear as possible, but I apologise if it doesn't meet the required standards.
As part of a summer project, I am taking time-lapse images of an internal melt figure growing inside a crystal of ice. For each of these images I would like to measure the perimeter of, and area enclosed by the figure formed. Linked below is an example of one of my images:
The method that I'm trying to use is the following:
Load image, crop, and convert to grayscale
Process to reduce noise
Find edge/perimeter
Attempt to join edges
Fill perimeter with white
Measure Area and Perimeter using regionprops
This is the code that I am using:
clear; close all;
% load image and convert to grayscale
tyrgb = imread('TyndallTest.jpg');
ty = rgb2gray(tyrgb);
figure; imshow(ty)
% apply a weiner filter to remove noise.
% N is a measure of the window size for detecting coherent features
N=20;
tywf = wiener2(ty,[N,N]);
tywf = tywf(N:end-N,N:end-N);
% rescale the image adaptively to enhance contrast without enhancing noise
tywfb = adapthisteq(tywf);
% apply a canny edge detection
tyedb = edge(tywfb,'canny');
%join edges
diskEnt1 = strel('disk',8); % radius of 4
tyjoin1 = imclose(tyedb,diskEnt1);
figure; imshow(tyjoin1)
It is at this stage that I am struggling. The edges do not quite join, no matter how much I play around with the morphological structuring element. Perhaps there is a better way to complete the edges? Linked is an example of the figure this code outputs:
The reason that I am trying to join the edges is so that I can fill the perimeter with white pixels and then use regionprops to output the area. I have tried using the imfill command, but cannot seem to fill the outline as there are a large number of dark regions to be filled within the perimeter.
Is there a better way to get the area of one of these melt figures that is more appropriate in this case?
As background research: I can make this method work for a simple image consisting of a black circle on a white background using the below code. However I don't know how edit it to handle more complex images with edges that are less well defined.
clear all
close all
clc
%% Read in RGB image from directory
RGB1 = imread('1.jpg') ;
%% Convert RPG image to grayscale image
I1 = rgb2gray(RGB1) ;
%% Transform Image
%CROP
IC1 = imcrop(I1,[74 43 278 285]);
%BINARY IMAGE
BW1 = im2bw(IC1); %Convert to binary image so the boundary can be traced
%FIND PERIMETER
BWP1 = bwperim(BW1);
%Traces perimeters of objects & colours them white (1).
%Sets all other pixels to black (0)
%Doing the same job as an edge detection algorithm?
%FILL PERIMETER WITH WHITE IN ORDER TO MEASURE AREA AND PERIMETER
BWF1 = imfill(BWP1); %This opens figure and allows you to select the areas to fill with white.
%MEASURE PERIMETER
D1 = regionprops(BWF1, 'area', 'perimeter');
%Returns an array containing the properties area and perimeter.
%D1(1) returns the perimeter of the box and an area value identical to that
%perimeter? The box must be bounded by a perimeter.
%D1(2) returns the perimeter and area of the section filled in BWF1
%% Display Area and Perimeter data
D1(2)
I think you might have room to improve the effect of edge detection in addition to the morphological transformations, for instance the following resulted in what appeared to me a relatively satisfactory perimeter.
tyedb = edge(tywfb,'sobel',0.012);
%join edges
diskEnt1 = strel('disk',7); % radius of 4
tyjoin1 = imclose(tyedb,diskEnt1);
In addition I used bwfill interactively to fill in most of the interior. It should be possible to fill the interior programatically but I did not pursue this.
% interactively fill internal regions
[ny nx] = size(tyjoin1);
figure; imshow(tyjoin1)
tyjoin2=tyjoin1;
titl = sprintf('click on a region to fill\nclick outside window to stop...')
while 1
pts=ginput(1)
tyjoin2 = bwfill(tyjoin2,pts(1,1),pts(1,2),8);
imshow(tyjoin2)
title(titl)
if (pts(1,1)<1 | pts(1,1)>nx | pts(1,2)<1 | pts(1,2)>ny), break, end
end
This was the result I obtained
The "fractal" properties of the perimeter may be of importance to you however. Perhaps you want to retain the folds in your shape.
You might want to consider Active Contours. This will give you a continous boundary of the object rather than patchy edges.
Below are links to
A book:
http://www.amazon.co.uk/Active-Contours-Application-Techniques-Statistics/dp/1447115570/ref=sr_1_fkmr2_1?ie=UTF8&qid=1377248739&sr=8-1-fkmr2&keywords=Active+shape+models+Andrew+Blake%2C+Michael+Isard
A demo:
http://users.ecs.soton.ac.uk/msn/book/new_demo/Snakes/
and some Matlab code on the File Exchange:
http://www.mathworks.co.uk/matlabcentral/fileexchange/28149-snake-active-contour
and a link to a description on how to implement it: http://www.cb.uu.se/~cris/blog/index.php/archives/217
Using the implementation on the File Exchange, you can get something like this:
%% Load the image
% You could use the segmented image obtained previously
% and then apply the snake on that (although I use the original image).
% This will probably make the snake work better and the edges
% in your image is not that well defined.
% Make sure the original and the segmented image
% have the same size. They don't at the moment
I = imread('33kew0g.jpg');
% Convert the image to double data type
I = im2double(I);
% Show the image and select some points with the mouse (at least 4)
% figure, imshow(I); [y,x] = getpts;
% I have pre-selected the coordinates already
x = [ 525.8445 473.3837 413.4284 318.9989 212.5783 140.6320 62.6902 32.7125 55.1957 98.6633 164.6141 217.0749 317.5000 428.4172 494.3680 527.3434 561.8177 545.3300];
y = [ 435.9251 510.8691 570.8244 561.8311 570.8244 554.3367 476.3949 390.9586 311.5179 190.1085 113.6655 91.1823 98.6767 106.1711 142.1443 218.5872 296.5291 375.9698];
% Make an array with the selected coordinates
P=[x(:) y(:)];
%% Start Snake Process
% You probably have to fiddle with the parameters
% a bit more that I have
Options=struct;
Options.Verbose=true;
Options.Iterations=1000;
Options.Delta = 0.02;
Options.Alpha = 0.5;
Options.Beta = 0.2;
figure(1);
[O,J]=Snake2D(I,P,Options);
If the end result is an area/diameter estimate, then why not try to find maximal and minimal shapes that fit in the outline and then use the shapes' area to estimate the total area. For instance, compute a minimal circle around the edge set then a maximal circle inside the edges. Then you could use these to estimate diameter and area of the actual shape.
The advantage is that your bounding shapes can be fit in a way that minimizes error (unbounded edges) while optimizing size either up or down for the inner and outer shape, respectively.