CC.PixelIdxList{idx}
會給你在哪裏你的對象位於圖像中的位置的線性指標。
您可以使用ind2sub
將線性索引轉換爲行和列位置,然後我們可以確定這些行和列索引的左上角和右下角。一旦我們這樣做,我們就可以相應地標記你的圖像。
因此:
%// Determine row and column locations
[row,col] = ind2sub(size(BW), CC.PixelIdxList{idx});
%// Get top left and bottom right coordinates
topleft_row = min(row);
topleft_col = min(col);
bottomright_row = max(row);
bottomright_col = max(col);
%// Draw a white box around the object
%// Left vertical line
BW(topleft_row:bottomright_row, topleft_col) = true;
%// Right vertical line
BW(topleft_row:bottomright_row, bottomright_col) = true;
%// Top horizontal line
BW(topleft_row, topleft_col:bottomright_col) = true;
%// Bottom horizontal line
BW(bottomright_row, topleft_col:bottomright_col) = true;
這裏使用的內置到MATLAB coins.png
的例子。我在圖像中閱讀,將其限定並填入洞中。
im = imread('coins.png');
BW = im2bw(im, graythresh(im));
BW = imfill(O, 'holes');
當我做到這一點,運行上面的代碼周圍繪製的最大目標的矩形,這就是我得到:
![enter image description here](https://i.stack.imgur.com/FB8On.png)
如果這個代碼關係到你的程序,不要做任何掩蔽。上述替換掩蔽代碼...所以:
f = imread('test.PNG');
subplot(2,2,1); imshow(f,[]); title('Original Image');
for i = 1:3
Image = medfilt2(Image,[3 3]);
end
[Image_Num, num] = bwlabel(Image,8);
subplot(2,2,3); imshow(Image); title('after median filtering'); %labeling algorithm
BW=im2bw(Image);
subplot(2,2,4); imshow(BW); title('binary image');
CC = bwconncomp(BW); %area based segmentation
numPixels = cellfun(@numel,CC.PixelIdxList);
[biggest,idx] = max(numPixels);
%-------- CHANGE HERE
%// Determine row and column locations
[row,col] = ind2sub(size(BW), CC.PixelIdxList{idx});
%// Get top left and bottom right coordinates
topleft_row = min(row);
topleft_col = min(col);
bottomright_row = max(row);
bottomright_col = max(col);
%// Draw a white box around the object
%// Left vertical line
BW(topleft_row:bottomright_row, topleft_col) = true;
%// Right vertical line
BW(topleft_row:bottomright_row, bottomright_col) = true;
%// Top horizontal line
BW(topleft_row, topleft_col:bottomright_col) = true;
%// Bottom horizontal line
BW(bottomright_row, topleft_col:bottomright_col) = true;
你有沒有考慮過使用'rectangle'註解函數? – Shai