# How to automatically obtain shape coordinates

3 views (last 30 days)
Jacob Ebilane on 24 Jan 2022
Answered: Image Analyst on 25 Jan 2022
I have an image (attached) that I want to crop. But to crop them I always need to manually take the center "coordinates" (index) of the center of each black box in the red circle. I need to automate it but I don't know where to start. Matt J on 24 Jan 2022
Edited: Matt J on 24 Jan 2022
Perhaps as follows
B=medfilt2(A,[5,5])<60;
B=bwareafilt(B,5) & ~bwareafilt(B,1);
T=regionprops('table',B,'Centroid'); %square centroids
LT=min(T.Centroid); %%left top corner
SZ=max(T.Centroid)-LT+1; %size fo box
A=imcrop(A,[LT,SZ]); %ignore projective warping
imshow(A,[]) ##### 2 CommentsShowHide 1 older comment
Matt J on 25 Jan 2022
You have the 4 points in T.Centroid.

yanqi liu on 25 Jan 2022
clc; clear all; close all;
if ndims(img) == 3
img = rgb2gray(img);
end
bw2 = ~bw;
bw2 = imopen(bw2, strel('square', 5));
bw3 = imclose(bw2, strel('line', size(bw2,1), 90));
bw4 = imclose(bw2, strel('line', size(bw2,2), 0));
% find left and right
[L,num] = bwlabel(bw3);
stats = regionprops(L);
rects = cat(1, stats.BoundingBox);
ind1 = find(rects(:,4)>size(bw2,1)*0.8);
[~,ind2] = min(rects(ind1,1));
[~,ind3] = max(rects(ind1,1));
bw3 = L==ind1(ind2) | L == ind1(ind3);
% find top and bottom
[L,num] = bwlabel(bw4);
stats = regionprops(L);
rects = cat(1, stats.BoundingBox);
ind1 = find(rects(:,3)>size(bw2,2)*0.8);
[~,ind2] = min(rects(ind1,2));
[~,ind3] = max(rects(ind1,2));
bw4 = L==ind1(ind2) | L == ind1(ind3);
% make square
bw5 = logical(bw3 + bw4);
bw5 = imfill(bw5, 'holes');
[r,c] = find(bw5);
rect = [min(c) min(r) max(c)-min(c) max(r)-min(r)];
% get 4 square
figure; imshow(img);
hold on; rectangle('position', rect, 'EdgeColor', 'g', 'LineWidth', 2) Image Analyst on 25 Jan 2022
Here is yet another way:
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Image.')
if ndims(grayImage) == 3
grayImage = rgb2gray(grayImage);
end
topHatImage = imbothat(grayImage, true(51));
subplot(2, 2, 2);
imshow(topHatImage, [])
title('Top Hat Filtered Image.')
impixelinfo;
allAreas = sort([props.Area])
subplot(2, 2, 3);
croppedImage = imcrop(grayImage, props.BoundingBox);
subplot(2, 2, 4);
imshow(croppedImage, []);
title('Cropped Image.') It could be made faster if you started with a good image, like one from a scanner instead of a poorly lit paper and a mobile phone camera.

R2021a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!