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

Matlab 如何使用ginput剪切图像的一小部分?,matlab,image-processing,Matlab,Image Processing,我有一个图像,我想用ginput剪切图像的一个小区域。我用下面的代码得到了一个矩形。如何在这个区域剪切图像 [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)

我有一个图像,我想用ginput剪切图像的一个小区域。我用下面的代码得到了一个矩形。如何在这个区域剪切图像

[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));

对于您的解决方案,两个输入可能就足够了,即对角线点。感谢@SanthanSalai提供的有效点。我已根据您的建议更新了答案。如何在剪切前缩放图像?您可以在imshow之前使用imresize来缩放原始图像。@leenasilvoster当然,我使用的图像是三维图像。虽然
bw
是二维的,但我想将其(即
bw
-第一个参数)复制到与原始图像大小相同的三维空间。所以
大小(img,3)
。我不想改变第一和第二维度。所以
1,1
我说得清楚了吗?@leenasilvoster,这可能是版本问题。你犯了什么错误?@leenasilvoster这是版本问题。检查编辑。。我希望如此works@leenasilvoster,你看到白色背景了吗?这是因为,对于
uint8
图像,
255
表示白色,而
0
表示黑色。而对于
double
图像,
0
表示黑色,
1
表示白色。让我们。