简体   繁体   English

如何从MATLAB中4个角点指定的图像中裁剪一部分

[英]How can I crop a portion from an image specified by 4 corner points in MATLAB

I want to crop only the portion closed by red lines in this image:- 我只想裁剪此图中用红线封闭的部分:-

I have the four corner points (x1,y1) , (x2,y2) , (x3,y3) , (x4,y4) . 我有四个角点(x1,y1)(x2,y2)(x3,y3)(x4,y4) I tried imcrop but that's for rectangular crop. 我试过imcrop但这是用于矩形作物。 Output image needs to be RGB. 输出图像必须是RGB。

I used google search to find your original image file :- 我用谷歌搜索来找到您的原始图像文件 :-

原始文件

Now, if I understand your question correctly, this is what you're looking for: 现在,如果我正确理解了您的问题,那么您正在寻找的是:

I=imread('nYNKB.jpg');
Isize = size(I);

mask = poly2mask([43 214 227 123],[131 22 112 198],Isize(1,1),Isize(1,2));
% where [x1,x2,x3,x4] = [43 214 227 123] & [y1,y2,y3,y4] = [131 22 112 198]

I_masked = bsxfun(@times,I,cast(mask,class(I)));

subplot(1,2,1)
imshow(I);
title('Original Image')

subplot(1,2,2)
imshow(I_masked)
title('Masked Image')

Output:- 输出:- 产量


Edit:- 编辑:-

If you do not want the black background, the closest you can go is with this: 如果您不想使用黑色背景,则可以使用以下方法:

figure(2)
mask = bsxfun(@eq,I_masked,reshape([0 0 0],1,1,3));
image(I_masked,'alphadata',1-double(all(mask,3)));
axis off
title('Masked Image')

Output:- 输出:-

输出1



Alternate Solution (if output does not have to be RGB) :- 替代解决方案(如果输出不必是RGB):-

I = rgb2gray(imread('nYNKB.jpg'));
imshow(I);
h = imfreehand; 
M = ~h.createMask();
I(M) = 0;
imshow(I);


gif_output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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