Basically what I'm trying to do is using predefined ROI's to crop and image into multiple new images.
Longer is that I have a map of brain, with sections of it defined. using that I define many ROI's from it in MATLAB using imfreehand or roipoly. From there I have stained slides of these sections. I want to use the ROI's that I defined from the map to crop the image of the real brain into many new images.
Just having trouble finding something that uses the ROI's as the cropping area and not just some rectangle.
If I need to explain a bit more let me know.
Simple example of what I think you want using imfreehand:
I = imread('pout.tif');
imshow(I);
h = imfreehand; % now pick ROI
BW = createMask(h); % get BW mask for that ROI
pos = getPosition(h); % get position for that ROI
% define bounding box
x1 = round(min(pos(:,2)));
y1 = round(min(pos(:,1)));
x2 = round(max(pos(:,2)));
y2 = round(max(pos(:,1)));
I2 = I.*uint8(BW); % apply mask to image
I2 = I2(x1:x2,y1:y2);
figure;
subplot(1,2,1);
imshow(I);
subplot(1,2,2);
imshow(I2);
If you have the ROI's already saved in some way, and don't want to run imfreehand again, all you really need is to calculate BW (a mask with ones within the ROI and zeros elsewhere) and the bounding box (to crop tight around the ROI).
Related
what I am trying is to compare two gray scale images by ploting their intensity into graph. The code is bellow is for single image.
img11 = imread('img.bmp');
[rows cols ColorChannels] = size(img11);
for i=1:cols
for j=1:rows
intensityValue = img11(j,i);
end
end
% below trying different plot method
plot(intensityValue);
plot(1:length(img11),img11);
plot(img11(:))
My expected result for two images is like below pictures: here
not like
this here
Based on your code you should be able to do the following.
img11 = imread('img1.bmp');
img22 = imread('img2.bmp');
figure;
imagesc(img11); % verify you image
figure;
plot(img11(:)); hold on;
plot(img22(:));
Using the command (:) will flatten a matrix into a single vector starting at the top left and going down in columns. If that is not the orientation that you want you try to rotate/transpose the image (or try using reshape(), but it might be confusing at the start). Additionally, if your image has large variations in the pixel intensity moving average filter can be useful.
Len = 128;
smooth_vector = filter(ones(Len,1)/Len,1,double(img11(:)));
figure; plot(smooth_vector);
I am trying to find a way to crop from a circle object (Image A) the largest square that can fit inside it.
Can someone please explain/show me how to find the biggest square fit parameters of the white space inside the circle (Image I) and based on them crop the square in the original image (Image A).
Script:
A = imread('E:/CirTest/Test.jpg');
%imshow(A)
level = graythresh(A);
BW = im2bw(A,level);
%imshow(BW)
I = imfill(BW, 'holes');
imshow(I)
d = imdistline;
[centers, radii, metric] = imfindcircles(A,[1 500]);
imageCrop=imcrop(A, [BoxBottomX BoxBottomY NewX NewY]);
I have a solution for you but it requires a bit of extra work. What I would do first is use imfill but directly on the grayscale image. This way, noisy pixels in uniform areas get inpainted with the same intensities so that thresholding is easier. You can still use graythresh or Otsu's thresholding and do this on the inpainted image.
Here's some code to get you started:
figure; % Open up a new figure
% Read in image and convert to grayscale
A = rgb2gray(imread('http://i.stack.imgur.com/vNECg.jpg'));
subplot(1,3,1); imshow(A);
title('Original Image');
% Find the optimum threshold via Otsu
level = graythresh(A);
% Inpaint noisy areas
I = imfill(A, 'holes');
subplot(1,3,2); imshow(I);
title('Inpainted image');
% Threshold the image
BW = im2bw(I, level);
subplot(1,3,3); imshow(BW);
title('Thresholded Image');
The above code does the three operations that I mentioned, and we see this figure:
Notice that the thresholded image has border pixels that need to be removed so we can concentrate on the circular object. You can use the imclearborder function to remove the border pixels. When we do that:
% Clear off the border pixels and leave only the circular object
BW2 = imclearborder(BW);
figure; imshow(BW2);
... we now get this image:
Unfortunately, there are some noisy pixels, but we can very easily use morphology, specifically the opening operation with a small circular disk structuring element to remove these noisy pixels. Using strel with the appropriate structuring element in addition to imopen should help do the trick:
% Clear out noisy pixels
SE = strel('disk', 3, 0);
out = imopen(BW2, SE);
figure; imshow(out);
We now get:
This mask contains the locations of the circular object we now need to use to crop our original image. The last part is to determine the row and column locations using this mask to locate the top left and bottom right corner of the original image and we thus crop it:
% Find row and column locations of circular object
[row,col] = find(out);
% Find top left and bottom right corners
top_row = min(row);
top_col = min(col);
bottom_row = max(row);
bottom_col = max(col);
% Crop the image
crop = A(top_row:bottom_row, top_col:bottom_col);
% Show the cropped image
figure; imshow(crop);
We now get:
It's not perfect, but it will of course get you started. If you want to copy and paste this in its entirety and run this on your computer, here we are:
figure; % Open up a new figure
% Read in image and convert to grayscale
A = rgb2gray(imread('http://i.stack.imgur.com/vNECg.jpg'));
subplot(2,3,1); imshow(A);
title('Original Image');
% Find the optimum threshold via Otsu
level = graythresh(A);
% Inpaint noisy areas
I = imfill(A, 'holes');
subplot(2,3,2); imshow(I);
title('Inpainted image');
% Threshold the image
BW = im2bw(I, level);
subplot(2,3,3); imshow(BW);
title('Thresholded Image');
% Clear off the border pixels and leave only the circular object
BW2 = imclearborder(BW);
subplot(2,3,4); imshow(BW2);
title('Cleared Border Pixels');
% Clear out noisy pixels
SE = strel('disk', 3, 0);
out = imopen(BW2, SE);
% Show the final mask
subplot(2,3,5); imshow(out);
title('Final Mask');
% Find row and column locations of circular object
[row,col] = find(out);
% Find top left and bottom right corners
top_row = min(row);
top_col = min(col);
bottom_row = max(row);
bottom_col = max(col);
% Crop the image
crop = A(top_row:bottom_row, top_col:bottom_col);
% Show the cropped image
subplot(2,3,6);
imshow(crop);
title('Cropped Image');
... and our final figure is:
You can use bwdist with L_inf distance (aka 'chessboard') to get the axis-aligned distance to the edges of the region, thus concluding the dimensions of the largest bounded box:
bw = imread('http://i.stack.imgur.com/7yCaD.png');
lb = bwlabel(bw);
reg = lb==2; %// pick largest area
d = bwdist(~reg,'chessboard'); %// compute the axis aligned distance from boundary inward
r = max(d(:)); %// find the largest distance to boundary
[cy cx] = find(d==r,1); %// find the location most distant
boundedBox = [cx-r, cy-r, 2*r, 2*r];
And the result is
figure;
imshow(bw,'border','tight');
hold on;
rectangle('Position', boundedBox, 'EdgeColor','r');
Once you have the bounding box, you can use imcrop to crop the original image
imageCrop = imcrop(A, boundedBox);
Alternatively, you can
imageCrop = A(cy + (-r:r-1), cx + (-r:r-1) );
I have two sets of images of different size for each set. The first set is images of 400x400 pixels with real picture objects.
The second set is 319x319, with image silhouettes of different scale than the real picture objects.
What I want to achieve, is basically to have the silhouettes replaced by the real picture objects (i.e. beaver) of the first set. So the end result will be 319x319 resolution images with real picture objects. Here is an example:
The first set images cannot simply be resized to 319x319, since the beaver will not match the silhouette. There are about 100 images with different "beaver size to beaver's silhouette size" relationships. Is there a way to automate this procedure?
So far, I've tried #cxw suggestion up to step 2. Here is the code of EllipseDirectFit I used. And here is my code to plot the images with the ellipse fits. I don't know how to proceed to steps 3-5.. I think from EllipseDirectFit function -> 2*abs(A(1)) should be the ellipsi's major axes. (NOTE: 'a1.bmp' is the real image and 'b1.bmp' is the silhouette).
In case anyone else has the same problem as me, I post the code that solved my problem. I actually followed cxw's suggestion and fitted an ellipse for both real and silhouette pictures, then resized the real picture based on the ratio of the silhouette-ellipse's major axis to the real-ellipse major axis. This made the image object match in size the silhouette image object (i.e. the beaver). Then I either cropped, or added border pixels to match the resolution I needed (i.e. 319x319).
% fetching the images
realList = getAllFiles('./real_images'); % getAllFiles => StackOverflow function
silhList = getAllFiles('./silhouettes');
for qq = 1:numel(realList)
% Name of the file to save
str = realList{qq}(15:end);
a = imread(realList{qq}); % assign real image
background_Ra = a(1,1,1); % getting the background colors
background_Ga = a(1,1,2);
background_Ba = a(1,1,3);
% finding the points (x,y) to pass to fit_ellipse
[x1,y1]=find(a(:,:,1)~=background_Ra | a(:,:,2)~=background_Ga | a(:,:,3)~=background_Ba);
% fitting an ellipse to these points
z1 = fit_ellipse(x1,y1); % Mathworks file exchange function
b = imread(silhList{qq}); % assign silhouette image
background_R2b = b(1,1,1); % getting the background colors
background_G2b = b(1,1,2);
background_B2b = b(1,1,3);
% finding the points (x,y) to pass to fit_ellipse
[x2,y2]=find(b(:,:,1)~=background_R2b & b(:,:,2)~=background_G2b & b(:,:,3)~=background_B2b);
% fitting an ellipse to these points
z2 = fit_ellipse(x2,y2);
% ratio of silhouette's ellipse major axis to real image's ellipse
% major axis
ellaxratio = z2.long_axis/z1.long_axis;
% resizing based on ellaxratio, so that the real image object size will
% now fit the silhouette's image object size
c = imresize(a,ellaxratio); c = rgb2gray(c);
bordercolor = c(end,end);
% if the resulting image is smaller, add pixels around it until they
% match with the silhouette image resolution
if size(c) < 319
while size(c) < 319
% 'addborder' is a Mathworks file exchange function
c = addborder(c(:,:,1),1, bordercolor ,'outer');
end
% if the resulting image is larger, crop pixels until they match
else size(c) > 319
while size(c) > 319
c = c(2:end-1,2:end-1);
end
end
% in a few cases, the resulting resolution is 318x318, instead of
% 319x319, so a small adjustment won't hurt.
if size(c) ~= 319
c = imresize(c,[319 319]);
end
% saving..
imwrite(c,['./good_fits/' str '.bmp'])
end
I don't have code for this, but here's how I would proceed, just off-hand. There's almost certainly a better way :) .
For each of the real image and the silhouette image:
Get the X, Y coordinates of the pixels that aren't the background. Edit Example tested in Octave:
background_R = img(1,1,1)
background_G = img(1,1,2)
background_B = img(1,1,3)
[xs,ys]=find(img(:,:,1)~=background_R | img(:,:,2)~=background_G | img(:,:,3)~=background_B)
The logical OR is because the image can differ from the background in any color component.
Fit an ellipse to the X, Y coordinate pairs you found. E.g., use this routine from File Exchange. (Actually, I suppose you could use a circle fit or any other shape fit you wanted, as long as size and position are the only differences between the non-background portions of the images.)
Now you have ellipse parameters for the real image and the silhouette image. Assuming the aspect ratios are the same, those ellipses should differ only in center and scale.
Resize the real image (imresize) based on the ratio of silhouette ellipse major axis length to real image ellipse major axis length. Now they should be the same size.
Find the centers. Using the above fit routine,
A=EllipseDirectFit(...)
% switch to Mathworld notation from http://mathworld.wolfram.com/Ellipse.html
ma=A(1); mb=A(2)/2; mc=A(3); md=A(4)/2; mf=A(5)/2; mg=A(6);
center_x = (mc*md-mb*mf)/(mb**2-ma*mc)
center_y = (ma*mf-mb*md)/(mb**2-ma*mc)
Move the real image data in a 3-d matrix so that the ellipse centers
coincide. For example,
cx_silhouette = ... (as above, for the silhouette image)
cy_silhouette = ...
cx_real = ... (as above, for the *resized* real image)
cy_real = ...
shifted = zeros(size(silhouette_image)) % where we're going to put the real image
deltax = cx_silhouette - cx_real
deltay = cy_silhouette - cy_real
% if deltax==deltay==0, you're done with this step. If not:
portion = resized_real_image(max(deltay,0):319-abs(deltay), max(deltax,0):319-abs(deltax), :); % or something like that - grab the overlapping part of the resized real image
shifted(max(deltay,0):min(deltay+319,319), max(deltax,0):min(deltax+319,319), :) = portion; % or something like that - slide the portion of the resized real image in x and y. Now _shifted_ should line up with the silhouette image.
Using the background color (or the black silhouette — same difference) as a mask, copy pixels from the resized, moved real image into the silhouette image.
Hope this helps!
I have an image with a white background and trying to extract the object within it using MATLAB. I tried different techniques (bounded box) but I am not getting desired results. I have tried this StackOverflow post but it isn't quite working: MATLAB Auto Crop
How I can extract the object? Any idea which technique is suitable?
The image is shown below:
I propose the following workflow:
Binarize the image
Get the centroid and orientation of the main object
Crop the image to set the center of the object at the center of the image
Rotate the object with respect to the center to compensate for the tilt
Crop again to get the object
In practice, step 1 turned out to be rather complicated to perform because of the shadow and of the not-so-well-defined boundaries between the white part of the object and the background. The trick I used relies on the fact that, because of the many details inside the object (and the jpg compression) there is a lot of "noise" all over it. So looking for edges combined with a BW-dilation produced a very decent binarized image. I then used regioprops to filter the small outliers and get the properties of the object.
Here is the code:
% --- Load image
Img = imread('Tilted.jpg');
% --- Binarisation
% Find edges and dilate to get a bloc
BW = edge(mean(Img,3),'sobel');
BW = imdilate(BW, strel('disk',5));
% Get BW image
RP = regionprops(BW, 'Area', 'PixelIdxList', 'Centroid', 'Orientation');
[~, i] = max([RP(:).Area]);
BW = Img(:,:,1)*0;
BW(RP(i).PixelIdxList) = 1;
x = RP(i).Centroid(1);
y = RP(i).Centroid(2);
theta = -RP(i).Orientation;
% imshow(BW)
% plot(x+[0 500*cos(theta*pi/180)], y+[0 500*sin(theta*pi/180)]);
% return
% --- First crop
w = min(x-1, size(Img,2)-x);
h = min(y-1, size(Img,1)-y);
C = Img(ceil(y-h):floor(y+h), ceil(x-w):floor(x+w),:);
% --- Rotate image
R = imrotate(C, theta);
R(R==0) = 255;
% --- Second crop
% Parameters (to adjust)
th = 70;
margin = 25;
% Remove grey levels
Rwg = std(double(R),0,3).^2;
% Get x-bounds
sx = sum(Rwg,1);
x1 = max(find(sx>prctile(sx,th), 1, 'first')-margin, 1);
x2 = min(find(sx>prctile(sx,30), 1, 'last')+margin, size(Rwg,1));
% Get y-bounds
sy = sum(Rwg,2);
y1 = max(find(sy>prctile(sy,th), 1, 'first')-margin, 1);
y2 = min(find(sy>prctile(sy,th), 1, 'last')+margin, size(Rwg,1));
Res = R(y1:y2, x1:x2, :);
% --- Display
imshow(Res)
Of course, if you have many different images to process this may not work every time. This code is only a starting point and you now have to modify it to meet your precise needs.
Best,
I'm trying to crop an image but not with a rectangle (like in imcrop()) but with a polygon that has four corners. I've searched a lot and discovered that I need to perform a homography to reajust the cropped polygon into a rectangle.
So I've used imcrop() to select a polygon in an image :
img = imread('pout.tif');
imshow(img);
h = impoly;
position = wait(h);
x1 = min(position(:, 1));
x2 = max(position(:, 1));
y1 = min(position(:, 2));
y2 = max(position(:, 2));
BW = createMask(h);
How could I use these two things to crop out an area in the shape of a polygon with four corners ?
First of all, it is a bad idea to transform the image for cropping. It will results in changing the content of the ROI with artifacts due to interpolation when applying the homography. In addition, if one day you want to turn into a ROI defined by more than 4 points, this approach doesn't apply anylonger.
Second, I make some minor changes to your script, like this:
img = imread('circuit.tif');
imshow(img);
h = impoly;
position = wait(h);
boundbox = [min(position(:,1)), ....
min(position(:,2)), ....
max(position(:,1))-min(position(:,1)), ....
max(position(:,2))-min(position(:,2))];
BW = createMask(h);
img = imcrop(uint8(BW).*img, boundbox);
imshow(img)
You were almost there ... just mask the ROI of the image you want and crop with the bounding box of the ROI. Here it puts 0 outside the mask; you can adapt differently if you want.
Try "impoly" function in MATLAB
refer http://www.mathworks.in/help/images/ref/impoly.html