简体   繁体   中英

Crop and transform image in Matlab

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM