Identifying an object and its centroid in an image and then cropping the original image based on this centroid

5 views (last 30 days)
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!

Accepted Answer

yanqi liu
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])
  3 Comments
Image Analyst
Image Analyst on 30 Sep 2021
What's the use case here? It seems very strange that someone would want to find watermelon slices one time and then touching rocks the next time. What is your application?
Sam
Sam on 7 Oct 2021
Hi,
Thanks for your comment!
I am working on vehicle detection by extracting frames from overhead drone videos. Here, I am trying to track a particular vehicle and crop the bigger image around that tracked vehicle.
For example, attached image 1 is the full size extracted image from the video, and I want to identifiy all the vehicles in this image (if possible). Then dectecting the white car (highlighted in image 2) and cropping the image around it.
It will be very helpful if you can give my some advice in this regard.

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!