find a rectangle in an image in matlab in matlab

Here's a simple approach to detecting rectangles in an image using MATLAB:

  1. Read the input image and convert it to grayscale
main.m
% read image 
img = imread('input_image.jpg');

% convert to grayscale
gray_img = rgb2gray(img);
97 chars
6 lines
  1. Apply edge detection to the grayscale image
main.m
% apply edge detection using Canny algorithm
edge_img = edge(gray_img, 'Canny', [0.1, 0.2]);
93 chars
3 lines
  1. Find contours in the edge image using bwboundaries function
main.m
% find all the boundary pixels in the edge image
[B,L] = bwboundaries(edge_img, 'noholes');

% get the number of boundaries found
num_boundaries = size(B,1);
158 chars
6 lines
  1. Loop through each boundary and check if it forms a rectangle using polyshape function
main.m
% set minimum and maximum threshold for rectangle area
min_area = 100;
max_area = 10000;

% set minimum and maximum threshold for rectangularity
min_rectangularity = 0.80;
max_rectangularity = 1.20;

% loop through each boundary
for i=1:num_boundaries
    % convert the boundary pixels into a polyshape object
    poly = polyshape(B{i}(:,2), B{i}(:,1));
    
    % compute the area of the polyshape
    area = poly.area;
    
    % compute the perimeter of the polyshape
    perimeter = poly.perimeter;
    
    % compute the rectangularity of the polyshape
    rectangularity = area / (perimeter^2);
    
    % check if the polyshape is a rectangle based on its area and rectangularity
    if (area > min_area) && (area < max_area) && ...
       (rectangularity > min_rectangularity) && (rectangularity < max_rectangularity)
        % plot the rectangle
        plot(poly,'Color','red');
    end
end
901 chars
30 lines

This approach should be able to detect most rectangular shapes in an image. However, it may not work well for images with highly irregular shapes or low image quality. Further optimization may be required for such scenarios.

gistlibby LogSnag