我正在尝试使用精确边缘检测来检测纯色背景上的对象。
我能够获得所有边缘并在它们周围绘制矩形,但我正在努力在所有矩形周围绘制一个矩形,以便用来裁剪对象。
我对以下代码(从原始图像中给出了上图)感到非常满意:
original = imread('1.jpg');
img = rgb2gray(original);
BW = edge(img,'canny',0.09);
[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
blobMeasurements = regionprops(logical(BW), 'BoundingBox');
numberOfBlobs = size(blobMeasurements, 1);
rects = [];
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];
plot(x, y, 'LineWidth', 2);
end
但我没有得到以下工作(我希望得到外部矩形并裁剪原始图像):
% get min max
xmin=min(rects(:,1));
ymin=min(rects(:,2));
xmax=max(rects(:,1)+rects(:,3));
ymax=max(rects(:,2)+rects(:,4));
% define outer rect:
outer_rect=[xmin ymin xmax-xmin ymax-ymin];
rect = rectangle('Position',outer_rect));
crop = imcrop(original,rect);
figure
imshow(crop);
答案 0 :(得分:0)
使用以下代码
original = imread('1.jpg');
img = rgb2gray(original);
BW = edge(img,'canny',0.08);
[B,L,N,A] = bwboundaries(BW);
for k=1:length(B),
if(~sum(A(k,:)))
boundary = B{k};
end
end
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));
ymin=min(rectCollection(:,2));
xmax=max(rectCollection(:,3));
ymax=max(rectCollection(:,4));
% define outer rect:
outer_rect=[xmin ymin xmax-xmin ymax-ymin];
crop = imcrop(original,outer_rect);
imshow(crop);