-9 matlab image-processing computer-vision edge-detection image-segmentation
我有这个电池的图像:

我想确定电池的尺寸(以像素为单位).
我遇到的问题是电池旋转了一个未知的角度.
如何检测此旋转电池的尺寸?
我在考虑这些算法步骤:
我有点缺乏经验,我很感激如何在Matlab中实现这些算法阶段.
谢谢
Sha*_*hai 40
将此视为Matlab图像处理的初学者教程.阅读所用命令的文档,尝试了解它们正在做什么以及为什么.
用于imread将图像读入3D矩阵.为方便起见,我们使用以下方法将其转换为double[0..1]范围im2double:
>> img = im2double( imread( 'path/to/battety.jpg' ) );
Run Code Online (Sandbox Code Playgroud)
您可以查看imgusing size命令的大小:
>> size( img )
ans =
1024 768 3
Run Code Online (Sandbox Code Playgroud)
您可以从结果中看到您的图像有1024行,768列和3个通道(红色,绿色和蓝色).
如您所见,电池明显比背景亮,无色.我们可以选择在最亮通道值与最暗通道值之间存在较大间隙的像素作为"电池"像素:
>> bw = (max(img,[],3)-min(img,[],3)) > 0.2;
Run Code Online (Sandbox Code Playgroud)
见max和min更多的细节.
还有其他方法来阈值图像,graythresh有关详细信息,请参阅.
使用imshow我们可以看到我们得到了什么:
>> imshow(bw,[],'border','tight');
Run Code Online (Sandbox Code Playgroud)

通常,人们使用形态学操作来改善阈值结果.
你可以使用imclose:
>> bw = imclose( bw, ones(25) );
Run Code Online (Sandbox Code Playgroud)
结果:

处理和处理bw图像的一个非常有用的命令是regionprops.它可以让你获得各种不错的属性.您将使用它来计算'Orientation'图像的"白色"/电池区域
>> st = regionprops( bw, 'Orientation' )
st =
Orientation: 52.8694
Run Code Online (Sandbox Code Playgroud)
如您所见,电池旋转了52.8度.
使用imrotate以"整顿"的电池
>> rbw = imrotate( bw, -st.Orientation );
Run Code Online (Sandbox Code Playgroud)
电池轴对齐后,您可以使用any以下方法将白色像素"投影"到水平轴和垂直轴上:
>> pc = any( rbw, 2 ); %// project all rows into a single column
>> pr = any( rbw, 1 ); %// project all columns into a single row
Run Code Online (Sandbox Code Playgroud)
现在,您需要在投影中找到设置为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
Run Code Online (Sandbox Code Playgroud)
一旦你有角的x,y坐标,你可以在旋转的图像上绘制它们:
>> imshow(rbw,[],'border','tight');
>> hold on;
>> plot( [fx tx tx fx fx], [fy fy ty ty fy], ':r', 'LineWidth',3);
Run Code Online (Sandbox Code Playgroud)
产量:

坐标是:
>> [fx fy tx ty]
ans =
406 608 866 733
Run Code Online (Sandbox Code Playgroud)
如您所见,您的电池长度为(866-406)像素,宽度为(733-608)像素.