Finding a largest rectangular object in binary image with minimum length and width
Show older comments
How to find a largest rectangular object in binary image. Any connected object should be ignored. The object should have a minimum length of 50 pixels and minimum width of 4 pixels. The examples images are attached.
Thanks
6 Comments
Image Analyst
on 23 Oct 2023
Not sure I understand. Each of the yellow shapes can be considered as a collection of many touching rectangles. And a huge number of them since they can be constructed in many different ways using differently shaped and sized rectangles. So should they all be ignored? You'd have nothing left.

Why do you say some of them have no rectangle in them.
In general to find the largest blob you can do
largestBlob = bwareafilt(binaryImage, 1);
but that works on all blobs, regardless if they're perfectly rectangular.
Az
on 23 Oct 2023
Image Analyst
on 24 Oct 2023
According to your definition, how many rectangles are in each image and where are they? Because I see either no rectangle at all, or a shape made up of many, many rectangles. Can you outline their bounding boxes in red or green or something so I can see where they are? Also, can you attach each image individually with the paper clip icon?
Walter Roberson
on 24 Oct 2023
The code I posted in my Answer searches for rectangles and throws away the ones that are too small, and finds the largest of what remains.
The remaining question is whether you did intend "width" to refer to horizontal extent, or if instead you are referring to "length" as the longer of (horizontal extent, vertical extent) and "width" as the smaller of the two ?
Walter Roberson
on 24 Oct 2023
When you indicated earlier that "Any connected object should be ignored" my understanding was that if you had rectangles that were connected to any other shape, that the entire blob should be ignored . That is why I coded regionprops to compare the convex area to the image area: those two values are only equal for blobs that are rectangles.
Answers (1)
Walter Roberson
on 22 Oct 2023
P = regionprops(YourBinaryImage, 'Area', 'ConvexArea', 'BoundingBox');
PA = vertcat(P.Area);
PCA = vertcat(P.ConvexArea);
PBB = vertcat(P.BoundingBox);
PW = PBB(:,3);
PH = PBB(:,4);
mask = PA == PCA & PH >= 50 & PW >= 4;
selected_P = P(mask);
[largest_object_area, idx] = max([selected_P.Area]);
largest_BB = selected_P(idx).BoundingBox;
Note that here I am interpreting "width" as horizontal extent, and then by default that means "length" in your question must refer to vertical extent.
Categories
Find more on Region and Image Properties in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!