Identifying an object and its centroid in an image and then cropping the original image based on this centroid
4 views (last 30 days)
Show older comments
Sam
on 29 Sep 2021
Commented: Dayangku Nur Faizah Pengiran Mohamad
on 19 May 2024
Hello,
I need to detect a particular objects out of many objects in an image. Then I need to find its centroid and then crop the image around that particular tracked object using its centroid as the centre of that rectangular crop.
For example, let's say I need to idenfity the marked watermelon piece (as in the attached picture) and then crop the image around this piece of watermelon.
Any help in this regard will be greatly appreciated. Thank you very much!
0 Comments
Accepted Answer
yanqi liu
on 30 Sep 2021
sir,please check the follow code to get some information
clc; clear all; close all;
img = imread('https://ww2.mathworks.cn/matlabcentral/answers/uploaded_files/753699/gas-x-summer-fruits-cause-bloating-main.jpg');
% colorspace
jmg = rgb2ycbcr(img);
jm = mat2gray(jmg(:,:,2));
jm = imcomplement(jm);
% thresh
bw = im2bw(jm, graythresh(jm));
% filter noise
bw = imopen(bw, strel('disk', 5));
bw = imfill(bw, 'holes');
% label every target
[L,num] = bwlabel(bw);
stats = regionprops(L);
figure; imshow(img, []);
for i = 1 : num
% get rect
recti = stats(i).BoundingBox;
% get cen
ceni = stats(i).Centroid;
% crop image
imi = imcrop(img, round(recti));
ims{i} = imi;
% rect and cen
hold on; rectangle('Position', recti, 'EdgeColor', 'c', 'LineWidth', 2);
plot(ceni(1), ceni(2), 'yp', 'MarkerFaceColor', 'y', 'MarkerSize', 16);
end
% make grid
sz = round(sqrt(length(ims)));
if sz*sz < length(ims)
sz = [sz+1 sz];
else
sz = [sz sz];
end
figure;
montage(ims, 'Size', sz, 'BackgroundColor', 'w', 'BorderSize', [3 3])
4 Comments
Dayangku Nur Faizah Pengiran Mohamad
on 19 May 2024
Hello Sam, I have tried your code to detect mine. But the codes could not find any object in my image. Could you please help me? Thanks in advance.
More Answers (0)
See Also
Categories
Find more on Image Segmentation and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!