简体   繁体   English

如何在此图片中检测具有特定尺寸的矩形,然后在Matlab中将矩形尺寸与预定尺寸进行比较?

[英]How can I detect a rectangle with a certain dimensions in this picture, and compare the rectangle dimensions with predetermined dimensions in Matlab?

This is a real image of a battery. 这是电池的真实图像。 I want to detect the smallest rectangular which contains the full battery. 我想检测包含整个电池的最小矩形。 Why do I want this? 我为什么要这个? Because I want to know the size of this rectangular so I can compare this size with predetermined dimensions. 因为我想知道此矩形的尺寸,所以可以将此尺寸与预定尺寸进行比较。 After comparing, the result has to be if this battery is an AA-battery for example. 比较之后,结果必须是例如该电池是否为AA电池。 Thanks. 谢谢。

在此处输入图片说明

You can apply a bit of pre-processing to your image (threshold on a particular channel, here the green channel) and a median filter to remove unwanted background signal. 您可以对图像进行一些预处理(特定通道的阈值,此处为绿色通道)和中值滤波器,以去除不需要的背景信号。

Then it's a matter of using regionprops to identify objects in the image. 然后是使用regionprops识别图像中的对象的问题。 The battery is the object with the largest area, so you can use the appropriate index from the structure returned by regionprops to get the size of the enclosing bounding box. 电池是面积最大的对象,因此您可以使用regionprops返回的结构中的适当索引来获取封闭边界框的大小。

clear
clc

%/ Read and pre-process the image to clear unwanted signal
Im = imread('Battery.jpg');
ImBW = im2bw(Im(:,:,2),.25);
ImBW = medfilt2(ImBW,[7 7]);

%// Detect objects in cleaned image
S = regionprops(ImBW,'BoundingBox','Area');

%// Identify battery as largest object
[MaxArea,MaxIndex] = max(vertcat(S.Area));

imshow(Im,'InitialMagnification',20)

%// Display results and message
hold on

rectangle('Position',S(MaxIndex).BoundingBox,'LineWidth',2,'EdgeColor','y')

Length = S(MaxIndex).BoundingBox(3);
Height = S(MaxIndex).BoundingBox(4);

message = sprintf('The height is %0.2f pixels \nand length is %0.2f pixels',Height,Length);

h = msgbox(message);

Cropped output: 裁剪后的输出:

在此处输入图片说明

Then you simply need to convert the pixel values into real units. 然后,您只需要将像素值转换为真实单位即可。 I'll let that part up to you. 我会让那部分交给你。

Have fun! 玩得开心!

No need to pay for Matlab, do it simply and for free at the commandline with ImageMagick which is installed on most Linux distros and availble for OSX and Windows. 无需为Matlab付费,只需在命令行中使用ImageMagick即可简单,免费地完成此操作,ImageMagick已安装在大多数Linux发行版中,并且适用于OSX和Windows。

convert battery.jpg -fuzz 50% -format "%@"  info:
1474x406+653+986

That tells us that, if we trimmed the background off, the remaining image (ie your battery) would be 1474 pixels wide and 406 pixels tall and located at coordinates 653,986 with respect to the top-left corner of the image. 这告诉我们,如果我们剪裁掉背景,则剩余图像(即您的电池)将为1474像素宽,406像素高,并且相对于图像的左上角位于坐标653986处。

Or this will actually extract it: 或实际上将其提取出来:

convert battery.jpg -fuzz 50% -trim result.jpg

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM