MATLAB Answers

How to automatically crop/trim specific region in several images automatically?

6 views (last 30 days)
There are many images in which i am interested in specific region. Below you will find the image in which i am interested only on the patterns(circle, cubes..,) in the image and i would like to crop outer boundary.Further i will use canny edge detector and calculate the dimensions of the patterns using regionprops. Can anyone help me with the code to automatically crop anything outside this patterns?contourresult_layer025.png

  0 Comments

Sign in to comment.

Accepted Answer

Vinai Datta Thatiparthi
Vinai Datta Thatiparthi on 26 Jul 2019
Hey Imran!
A simple way to solve this problem is to first crop, binarize and clean the image of noise, followed by finding the centroids and major/minor axes values using the command ‘regionprops’ and finally using the 'imcrop' function to get to your desired output.
To achieve the first step,
im = imread('figCrop.png'); % Read your image
im = rgb2gray(im); % Convert to grayscale
im1 = imcrop(im,[223 118, 1333, 1273]); % Crop the image appropriately
im2 = imbinarize(im1); % Binarize the image
im3 = imfill(im2, 'holes'); % Unnecessary, but you can include this as well
J = medfilt2(im3,[15 15]); % Apply median filtering, since salt&pepper noise
Secondly, use the MATLAB command ‘regionprops’ to extract the centroid values and minor/major axes lengths.
s = regionprops(J,'centroid');
centroids = cat(1,s.Centroid);
imshow(J)
hold on
plot(centroids(:,1),centroids(:,2),'b*') % Plot the centroids
hold off
stats = regionprops('table',J,'Centroid',...
'MajorAxisLength','MinorAxisLength'); % Save all the values in a table
This will result in a table ‘stats’ that holds all the centroid and axes length information. Note that there are a few additional unnecessary values since the image could not be cleaned completely. These values must be neglected.
Now, leverage this information in ‘stats’ to feed the data to ‘imcrop’command to get the desired outputs. You may automate this process by writing a code that iteratively moves through all the centroids and crop images according to minor/major axes values.
For further information on the command ‘regionprops’, refer the documentation at https://www.mathworks.com/help/images/ref/regionprops.html

  0 Comments

Sign in to comment.

More Answers (0)

Sign in to answer this question.