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. 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. 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.
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.
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.
Or this will actually extract it:
convert battery.jpg -fuzz 50% -trim result.jpg
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.