首页 文章

如何在MATLAB中检测此图片中某个角度下物体的尺寸? [关闭]

提问于
浏览
-9

我有这个电池的图像:

enter image description here

我想确定电池的尺寸(以像素为单位) .
我遇到的问题是电池旋转了一个未知的角度 .
如何检测此旋转电池的尺寸?

我在考虑这些算法步骤:

  • 首先,我必须将此图像转换为黑白图像(阈值处理) .

  • 之后,我必须找到一个中心点并在白色像素中绘制一个矩形 .

  • 然后,我必须将矩形旋转360度并找到矩形的位置(以及尺寸) .

我有点缺乏经验,我很感激如何在Matlab中实现这些算法阶段 .

谢谢

1 回答

  • 40

    将此视为Matlab图像处理的初学者教程 . 阅读所用命令的文档,然后尝试和 understand 他们正在做什么以及为什么 .

    1.阅读图片

    使用imread将图像读入3D矩阵 . 为方便起见,我们使用im2double将其转换为[0..1]范围内的 double

    >> img = im2double( imread( 'path/to/battety.jpg' ) );
    

    您可以使用size命令查看 img 的大小:

    >> size( img )
    ans =
        1024         768           3
    

    您可以从结果中看到您的图像有1024行,768列和3个通道(红色,绿色和蓝色) .

    2.转换为黑白(a.k.a thresholding)

    如您所见,电池明显比背景亮,无色 . 我们可以选择在最亮通道值与最暗通道值之间存在较大间隙的像素作为“电池”像素:

    >> bw = (max(img,[],3)-min(img,[],3)) > 0.2;
    

    有关详细信息,请参阅maxmin .
    还有其他方法可以对图像进行阈值处理,有关详细信息,请参阅graythresh .

    使用imshow我们可以看到我们得到了什么:

    >> imshow(bw,[],'border','tight');
    

    enter image description here

    通常使用morphological operations来改善阈值结果 .
    你可以使用imclose

    >> bw = imclose( bw, ones(25) );
    

    结果:

    enter image description here

    3.找到旋转角度

    用于处理和处理bw图像的非常有用的命令是regionprops . 它可以让你获得各种不错的属性 . 您将使用它来计算图像的"white" /电池区域的'Orientation'

    >> st = regionprops( bw, 'Orientation' )
    st = 
    Orientation: 52.8694
    

    如您所见,电池旋转了52.8度 .
    使用imrotate来"straighten"电池

    >> rbw = imrotate( bw, -st.Orientation );
    

    一旦电池轴对齐,您可以使用any将白色像素"project"水平轴和垂直轴上:

    >> pc = any( rbw, 2 ); %// project all rows into a single column 
    >> pr = any( rbw, 1 ); %// project all columns into a single row
    

    现在,您需要在投影中找到设置为1的第一个和最后一个像素 . 使用find

    >> fx = find( pr, 1, 'first');  %// first x coordinate
    >> tx = find( pr, 1, 'last');   %// last x coordinat
    >> fy = find( pc, 1, 'first');  %// first y coordinate
    >> ty = find( pc, 1, 'last');   %// last y coordinate
    

    一旦你有角的x,y坐标,你可以在旋转的图像上绘制它们:

    >> imshow(rbw,[],'border','tight');
    >> hold on; 
    >> plot( [fx tx tx fx fx], [fy fy ty ty fy], ':r', 'LineWidth',3);
    

    产量:

    enter image description here

    坐标是:

    >> [fx fy tx ty]
    ans =
    406   608   866   733
    

    如您所见,您的电池长度为(866-406)像素,宽度为(733-608)像素 .

相关问题