簡體   English   中英

Matlab從圖像裁剪多邊形

[英]Matlab crop a polygon from an image

我在穩定的背景上有產品的圖像,我想盡可能地裁切該產品。

原版的

我加亮它,並使用以下代碼查找邊緣:

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

這給了我以下圖片:

邊緣檢測

以下代碼為我在檢測到的每個斑點/線條上提供了矩形:

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

這給了我以下結果:

結果

我的問題是,如何使多邊形盡可能靠近產品並使用該多邊形進行裁剪,或者,如何使裁剪盡可能靠近產品及其上限?

如果您不想得到一個邊界框而是一個多邊形,我想您需要生成一個蒙版-一個具有相同圖像尺寸的矩陣,如果對象上的像素為1,則為0,否則為0。

我聽說過一種適用於套索的算法(抱歉,找不到名稱,如果找到它,我將對其進行編輯):

  • 步驟0:套索是邊界框。
  • 第i步:分割套索,如果圖像中的顏色(或任何其他)漸變小於固定值,則對每個零件進行縮回。
  • 步驟n(最后):您無法縮回套索的任何部分,它已經完成。 套索內部:對象。 外:背景。

我記得這種方法有很多工作:套索的定義,縮回步驟,套索的堅固性(避免套索變形太大)。

除了套索方法之外,您還可以搜索分水嶺變換 ,它也可以解決您的問題。

最后,如果生成圖片,請使用純色背景(綠色,粉紅色,藍色等)拍攝並使用簡單的摳像

使用活動輪廓看起來也不錯,但是要獲得漂亮的蒙版卻很麻煩。

original = imread('1.jpg');
level = graythresh(original);
img = rgb2gray(original);
mask = im2bw(img,level+0.1);

mask = imfill(~mask,'holes');

bw = activecontour(img,mask);

rows = numel(original(:,1,1));
columns = numel(original(1,:,1));

for i = 1:rows
    for j = 1:columns
        if (  bw(i,j,1) == 0 )
            original(i,j,:) = 255;
         end
    end
end

imshow(original);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM