如何使用ginput剪切一小部分图像?

how to cut a small portion of image using ginput?

我有一张图片,我想使用 ginput 剪切图片的一小块区域。我得到一个矩形,使用下面的code.how来切割这个区域的图像?

[x1 y1]=ginput(2);
[x2 y2]=ginput(2);
[x3 y3]=ginput(2);
[x4 y4]=ginput(2);

假设你想分离由4个用户输入标记的最大矩形区域,可以使用以下代码段对图像进行分割。如果它不能满足您的要求,请告诉我。

img = imread('cameraman.tif');
imshow(img);
[x, y] = ginput(4);
img2 = img(min(y):max(y),min(x):max(x));
imshow(img2);

假设只需要用户在目标区域的左上角和右下角点击两次来分割,上面的代码可以稍微修改如下。

img = imread('cameraman.tif');
imshow(img);
[x, y] = ginput(2);
img2 = img(min(y):max(y),min(x):max(x));
imshow(img2);

如果你想裁剪非矩形部分,试试这个

img = imread('hestain.png');

%// Display the image, so that the points could be selected over the image
imshow(img);
[x, y] = ginput(4);

%// getting logical matrix of the polygon formed out of the input points
bw = poly2mask( x, y, size(img,1),size(img,2));

%// replicating the logical array to form a 3D matrix for indexing
bw = repmat(bw,[1,1,size(img,3)]);

out = ones(size(img,1),size(img,2),size(img,3)).*255;
out(bw) = img(bw);

%// if you want the resultant image as same dimensions as of the original image
imshow(uint8(out));

%// if you want the resultant image to be cropped to minimum bounding rectangle
%// inspired from Hwathanie's answer
img2 = out(min(floor(y)):max(ceil(y)),min(floor(x)):max(ceil(x)),:);

figure;
imshow(uint8(img2));