MATLAB: How to counting the number car in a image

image processingImage Processing Toolbox

I'm working about detecting and counting cars but am counting wrong. In image I have 1 car but am counting many cars.
My code:
A=imread('1image_72.jpg');
figure,imshow(A); title('Original Image');
%Convert the Image to binary
B=im2bw(A);
%Fill the holes
C=imfill(B,'holes');
%Label the connected components
[Label,Total]=bwlabel(C,8);
figure,imshow(C); title('Labelled Image');
%Rectangle containing the region
Sdata=regionprops(Label,'BoundingBox');
%Crop all the Cars
for i=1:Total
Img=imcrop(A,Sdata(i).BoundingBox);
Name=strcat('Object Number:',num2str(i));
figure,imshow(Img); title(Name);
end

Best Answer

You're simply doing a auto threshold, which most likely gives a terrible segmentation, and then basically counting all bright blobs regardless if they're a car, a reflection, a part of a car, or anything else. You can't do anything as simplistic as a global threshold. Maybe you should try stdfilt() and try to get areas that have a lot of variation in them, assuming that the road or parking lot will be smooth. Then threshold the stdfilt() image.