2011-12-10 42 views
2

比方說,我有一個矩陣(由imread)如下:如何獲得MATLAB中非零元素的邊界框?

A = [0 0 1 0 0; 
    0 0 1 0 0; 
    0 1 1 1 0; 
    0 0 1 0 0; 
    0 0 0 0 0]; 

我想獲得非零元素的邊框作爲

BB = show_me_the_bounding_box(A); 
BB = [1, 2, 4, 4]; % y0, x0, y1, x0 

我應該使用什麼功能去做?

回答

2

爲了得到你想要的結果,請使用:

[y,x] = ind2sub(size(A), find(A)) 
coord = [y, x] 
[min(coord) max(coord)] % [1 2 4 4] 

然而要注意,用正確的約定,邊框是:

[y,x] = ind2sub(size(A), find(A)) 
coord = [x, y] 
mc = min(coord)-0.5 
Mc = max(coord)+0.5 
[mc Mc-mc] % [1.5 0.5 3 4] 

其結果如下:

stats = regionprops(A, 'BoundingBox') 
BB = stats.BoundingBox % [1.5 0.5 3 4] 

的代碼可以容易地通過使用被適配爲3D圖像:

[y,x,z] = ind2sub(size(A), find(A)); 
coord = [x, y, z]; 
mc = min(coord)-0.5; 
Mc = max(coord)+0.5; 
[mc Mc-mc] 
+0

我建議明確定義'min'和'max'的維度正在工作,例如, 'min(coord,[],1)'否則當你想綁定單個條目或點時,該方法將失敗。 – Maurits

3

使用REGIONPROPS

stats = regionprops(A,'BoundingBox'); 
BB = stats.BoundingBox; 
+0

有趣的是,'regionprops(A, '的BoundingBox')'將返回'1.5000 0.5000 3.0000 4.0000'〜 – Drake

+0

BB包含原點(1.5和0.5)和寬度(3和4),這給出了座標的[1.5 0.5 4.5 4.5],這是正確的。 – Wok

+0

順便說一下,BB可以很好地處理3D圖像。 – Wok

相關問題