The following code illustrates the working of regionprops()function to determine the boundary along with the connected components.
Assumption: It is assumed that the camera is fixed at a point and captures images.
clc
close all
clear
a= imread( 'car1.png'); %Read images
b = imread('car2.png');
a=rgb2gray(a);
b=rgb2gray(b);
d=a-b; %Background Substraction
BW=d;
BW=medfilt2(BW); %Median Filter
BW=edge(BW,'Canny',0.2); %Edge detection
se = strel('line',11,90); %Dilate Image
BW = imdilate(BW,se);
imshow(BW)
labeledImage = bwlabel(BW); %Labeling and Bounding Box around car
measurements = regionprops(labeledImage, 'BoundingBox', 'Area');
for k = 1 : length(measurements)
thisBB = measurements(k).BoundingBox;
rectangle('Position', [thisBB(1),thisBB(2),thisBB(3),thisBB(4)],...
'EdgeColor','r','LineWidth',2 )
end
b1=measurements(1).BoundingBox; %Measuring distance
b2=measurements(2).BoundingBox;
x1=b1(1,1)+b1(1,3)/2;
x2=b2(1,1)+b2(1,3)/2;
y1=b1(1,2)+b1(1,4)/2;
y2=b2(1,2)+b2(1,4)/2;
hold on
scatter(x1,y1);
scatter(x2,y2);
line([x1 x2], [y1 y2]);
distance=sqrt((x2-x1)^2 + (y2-y1)^2); %Distance
Output:
Refer to the following link for further information:
- https://www.mathworks.com/help/images/ref/regionprops.html(regionprops)
- https://www.mathworks.com/help/vision/examples/object-detection-using-faster-r-cnn-deep-learning.html(Object detection using R-CNN Deep Learning)
- https://www.mathworks.com/help/deeplearning/ug/pretrained-convolutional-neural-networks.html(Alternatively R-CNN could be used with the help of pre trained network)