如何在MATLAB中获取非零元素的边界框? [英] How to get the bounding box of non-zero elements in MATLAB?

查看:161
本文介绍了如何在MATLAB中获取非零元素的边界框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个矩阵(通过 imread )作为以下:

Let's say, I have a matrix (by imread) as following:

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

我想得到非零元素的边界框

I would like to get the bounding box of non-zero elements as

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

我应该使用什么功能?

推荐答案

要获得所需的结果,请使用:

To get the result you want, please use:

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

但是请注意,使用正确的约定,边界框为:

Note however that, with the correct conventions, the bounding box is:

[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]

产生与以下结果相同的结果:

which yields the same result as:

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

通过使用以下代码,可以轻松地将代码适应3D图像:

The code can easily be adapted to 3D images, by using:

[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]

这篇关于如何在MATLAB中获取非零元素的边界框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆