【发布时间】:2014-08-03 17:34:03
【问题描述】:
我有一张纯色背景上的产品图片,我想将其裁剪得尽可能靠近产品。
我把它变亮,用下面的代码找到边缘:
limits = stretchlim(original, 0.01);
img1 = imadjust(original, limits, []);
img = rgb2gray(img1);
BW = edge(img,'canny',0.2);
[B,L,N,A] = bwboundaries(BW);
figure; imshow(BW); hold on;
for k=1:length(B),
if(~sum(A(k,:)))
boundary = B{k};
plot(boundary(:,2),boundary(:,1),'r','LineWidth',2);hold on;
end
end
这给了我以下图片:
以下代码在检测到的每个 blob/行上为我提供了矩形:
blobMeasurements = regionprops(logical(BW), 'BoundingBox');
numberOfBlobs = size(blobMeasurements, 1);
rectCollection = [];
for k = 1 : numberOfBlobs % Loop through all blobs.
rects = blobMeasurements(k).BoundingBox; % Get list ofpixels in current blob.
x1 = rects(1);
y1 = rects(2);
x2 = x1 + rects(3);
y2 = y1 + rects(4);
x = [x1 x2 x2 x1 x1];
y = [y1 y1 y2 y2 y1];
rectCollection(k,:,:,:) = [x1; y1; x2; y2];
end
然后我可以绘制一个边界矩形并使用以下代码收集所有这些点进行裁剪:
% get min max
xmin=min(rectCollection(:,1))-1;
ymin=min(rectCollection(:,2))-1;
xmax=max(rectCollection(:,3))+1;
ymax=max(rectCollection(:,4))+1;
% define outer rect:
outer_rect=[xmin ymin xmax-xmin ymax-ymin];
crop = imcrop(original,outer_rect);
这给了我以下结果:
我的问题是如何让多边形尽可能靠近产品并用多边形裁剪它,或者只是尽可能靠近产品及其盖子进行裁剪?
【问题讨论】:
-
它是一个多边形重要还是只是一个边界?如果它可以是一个边界并且速度不是主要问题,那么 Active Countours 可能会有所帮助。看到这个答案:stackoverflow.com/a/18399089/2545927
-
Active Contours 可能有效,但它必须是自动的...有什么想法吗?
-
应用上面链接中的代码,看看你得到了什么。如果它不起作用,请阈值图像并查看。
-
仍在努力寻找一种可以始终如一地工作的体面方法
标签: matlab polygon crop bounding-box