You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
code to detection the cars this code not counting cars properly How do i make it count correct ?
1 view (last 30 days)
Show older comments
clc
clear all
MV = imread('cars1.jpg'); %To read image
MV1 = imread('backgnd.jpg');
A = double(rgb2gray(MV));%convert to gray
B= double(rgb2gray(MV1));%convert 2nd image to gray
[height, width] = size(A); %image size?
h1 = figure(1);
%Foreground Detection
thresh=11;
fr_diff = abs(A-B);
for j = 1:width
for k = 1:height
if (fr_diff(k,j)>thresh)
fg(k,j) = A(k,j);
else
fg(k,j) = 0;
end
end
end
subplot(2,2,1) , imagesc(MV), title (['Orignal Frame']);
subplot(2,2,2) , imshow(mat2gray(A)), title ('converted Frame');
subplot(2,2,3) , imshow(mat2gray(B)), title ('BACKGND Frame ');
36;
sd=imadjust(fg);% adjust the image intensity values to the color map
level=graythresh(sd);
m=imnoise(sd,'gaussian',0,0.025);% apply Gaussian noise
k=wiener2(m,[5,5]);%filtering using Weiner filter
bw=im2bw(k,level);
bw2=imfill(bw,'holes');
bw3 = bwareaopen(bw2,5000);
labeled = bwlabel(bw3,8);
cc=bwconncomp(bw3);
Densityoftraffic = cc.NumObjects/(size(bw3,1)*size(bw3,2));
blobMeasurements = regionprops(labeled,'all');
numberofcars = size(blobMeasurements, 1);
subplot(2,2,4) , imagesc(labeled), title (['Foreground']);
hold off;
disp(numberofcars);% display number of cars
disp(Densityoftraffic);%display number of vehicles
Accepted Answer
KSSV
on 18 Oct 2020
It looks like the dimensions of image A, B are not same. So while subtracting you are getting the error.
You need to resize them into same dimensions using imresize.
A = double(rgb2gray(MV));%convert to gray
B= double(rgb2gray(MV1));%convert 2nd image to gray
[m1,n1,p1] = size(A) ;
[m2,n2,p2] = size(B) ;
m = max(m1,m2) ;
n = max(n1,n2) ;
A = imresize(A,[m n]) ;
B = imresize(B, [m n]) ;
9 Comments
Jeje Ahmad
on 22 Oct 2020
can you help me the code does not count correct ; what is the value i will change to count correct ?
please
@KSSV
KSSV
on 24 Oct 2020
More Answers (1)
Image Analyst
on 24 Oct 2020
Here, try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 18;
fprintf('Beginning to run %s.m ...\n', mfilename);
% excel = actxserver('excel.application');
% filename = 'C:\Users\hayworth.ms\OneDrive - Procter and Gamble\Not Shared\Mark Hayworth Personal Files\Personal Documents\Financial Statements\Assets\ASSETS.xlsm';
% workbook = excel.Workbooks.Open(filename, [], true, [], 'images');
% excel.Visible = true;
MV = imread('cars1.png'); % To read image
MV1 = imread('backgnd.png');
carsImage = double(rgb2gray(MV));% convert to gray
[rows, columns, numColors] = size(carsImage)
backgroundImage = double(rgb2gray(MV1));%convert 2nd image to gray
[rowsb, columnsb, numColorsb] = size(backgroundImage)
% If the background image is not the same size as the test image, resize the test image.
if rows ~= rowsb || columns ~= columnsb
message = sprintf('Cars = %dx%d, background = %dx%d.\nI will resize the cars image.', rows, columns, rowsb, columnsb);
uiwait(helpdlg(message));
carsImage = imresize(carsImage, [rowsb, columnsb]);
[rows, columns, numColors] = size(carsImage)
end
% Display images.
subplot(2, 3, 1);
imshow(MV);
impixelinfo;
title('Cars1 image', 'FontSize', fontSize);
subplot(2, 3, 2);
imshow(MV1);
impixelinfo;
title('Background image', 'FontSize', fontSize);
h1 = figure(1);
%Foreground Detection
thresh=11;
fr_diff = imabsdiff(carsImage, backgroundImage);
subplot(2, 3, 3);
imshow(fr_diff, []);
impixelinfo;
title('Difference image', 'FontSize', fontSize);
% Take the histogram.
subplot(2, 3, 4);
histogram(fr_diff, 128);
% Put a line where the threshold is
xline(thresh, 'LineWidth', 2);
grid on;
title('Histogram of Difference Image', 'FontSize', fontSize);
% Threshold to create a binary image (mask)
mask = fr_diff > thresh;
subplot(2, 3, 5);
imshow(mask);
title('Thresholded image', 'FontSize', fontSize);
But rather than resizing, which doesn't allow for a perfect subtraction as you can see, you should really investigate why your frames are different sizes than your background image. And not only are they different sizes, but the cameras seem to be pointed in different directions so the field of view is not the same between the two cameras.
28 Comments
Jeje Ahmad
on 26 Oct 2020
i try it but give error
Undefined function or variable 'xline'.
Error in new (line 47)
xline(thresh, 'LineWidth', 2);
Image Analyst
on 26 Oct 2020
You have an old version. Try replacing xline with line:
line([thresh, thresh], ylim, 'LineWidth', 2);
Jeje Ahmad
on 26 Oct 2020
i try it and the code run code
but can i ask you
the code does not give the number of cars an image?
Image Analyst
on 26 Oct 2020
Correct. I did not do that part for you. Do you have a video? There is a demo in the Computer Vision Toolbox that does car counting.
Jeje Ahmad
on 27 Oct 2020
i open this toolbox and try to count cars but give not correctr
hoe i can add function to the code to counting cars?
@Image Analyst
Image Analyst
on 28 Oct 2020
Edited: Image Analyst
on 28 Oct 2020
I see you've already accepted an answer. Did it not really work? If not, unaccept it and maybe others will know it's not solved and open your post.
Like I said, you need to find out why your background is not the same size as your image, and why the camera does not have the same field of view (angle and field width) so that you can get better subtraction. Then you can just remove clutter with bwareaopen(), bwareafilt(), imclearborder(), imfill(), etc. and then call bwlabel to get the count.
Jeje Ahmad
on 28 Oct 2020
I see this toolbox but give my so error for the code
i just need a fuction added to the previous code to counting a cars?
@Image Analyst
Image Analyst
on 28 Oct 2020
From your response, I can see you haven't yet read this: TUTORIAL: How to ask a question (on Answers) and get a fast answer so read that first.
I see you've already accepted an answer. Did it not really work? If not, unaccept it and maybe others will know it's not solved and open your post.
Like I said, AGAIN you need to find out why your background is not the same size as your image, and why the camera does not have the same field of view (angle and field width) so that you can get better subtraction. Why won't you answer the one, main question that is the source of all your problems?
Here is a little bit more:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 18;
fprintf('Beginning to run %s.m ...\n', mfilename);
% excel = actxserver('excel.application');
% filename = 'C:\Users\hayworth.ms\OneDrive - Procter and Gamble\Not Shared\Mark Hayworth Personal Files\Personal Documents\Financial Statements\Assets\ASSETS.xlsm';
% workbook = excel.Workbooks.Open(filename, [], true, [], 'images');
% excel.Visible = true;
MV = imread('cars1.png'); % To read image
MV1 = imread('backgnd.png');
carsImage = double(rgb2gray(MV));% convert to gray
[rows, columns, numColors] = size(carsImage)
backgroundImage = double(rgb2gray(MV1));%convert 2nd image to gray
[rowsb, columnsb, numColorsb] = size(backgroundImage)
% If the background image is not the same size as the test image, resize the test image.
if rows ~= rowsb || columns ~= columnsb
message = sprintf('Cars = %dx%d, background = %dx%d.\nI will resize the cars image.', rows, columns, rowsb, columnsb);
uiwait(helpdlg(message));
carsImage = imresize(carsImage, [rowsb, columnsb]);
[rows, columns, numColors] = size(carsImage)
end
% Display images.
subplot(2, 3, 1);
imshow(MV);
impixelinfo;
title('Cars1 image', 'FontSize', fontSize);
subplot(2, 3, 2);
imshow(MV1);
impixelinfo;
title('Background image', 'FontSize', fontSize);
h1 = figure(1);
%Foreground Detection
thresh=11;
fr_diff = imabsdiff(carsImage, backgroundImage);
subplot(2, 3, 3);
imshow(fr_diff, []);
impixelinfo;
title('Difference image', 'FontSize', fontSize);
% Take the histogram.
subplot(2, 3, 4);
histogram(fr_diff, 128);
% Put a line where the threshold is
xline(thresh, 'LineWidth', 2);
grid on;
title('Histogram of Difference Image', 'FontSize', fontSize);
% Threshold to create a binary image (mask)
mask = fr_diff > thresh;
subplot(2, 3, 5);
imshow(mask);
title('Thresholded image', 'FontSize', fontSize);
% Filter out spurious blobs
mask = imfill(mask, 'holes');
mask = imclearborder(mask);
props = regionprops(mask, 'Area');
allAreas = sort([props.Area], 'descend')
mask = bwareafilt(mask, [100, inf]);
subplot(2, 3, 6);
imshow(mask);
title('Final Mask', 'FontSize', fontSize);
g = gcf;
g.WindowState = 'maximized';
fprintf('Done running %s.m ...\n', mfilename);
It still doesn't work great, again because you refuse to answer the questions about why the test image and the background don't correspond.
Image Analyst
on 29 Oct 2020
It shouldn't. That should work for every version of MATLAB since R2014b. For some reason you blew right past the version that you were supposed to enter when you posted your question but since that is a version that is over 6 years old, I assume you have R2020b and it should work. So the only other reason it wouldn't work with R2014b or later is if you didn't have the g=gcf line of code in there.
Regardless, it's just optional code to maximize the figure window and you can take it out if you want and the figure will show up "normalized" (non-full screen).
Jeje Ahmad
on 30 Oct 2020
i will take the picture it is the same size
but i want a function to added to count the number of cars
can you help me
please
Jeje Ahmad
on 12 Nov 2020
hi i am using this function but give me error
how i can correct this error
@Image Analyst
Jeje Ahmad
on 12 Nov 2020
Undefined function or variable 'Call'.
Error in new1 (line 78)
Call bwlabel()
Image Analyst
on 12 Nov 2020
Notice that I did not use the word "Call" which is not part of MATLAB syntax. I had this:
[labeledImage, numberOfCars] = bwlabel(binaryImage);
See? No "Call".
Jeje Ahmad
on 13 Nov 2020
yes i see
but give me this error
Undefined function or variable 'binaryImage'.
Error in new (line 69)
[labeledImage, numberOfCars] = bwlabel(binaryImage);
Image Analyst
on 14 Nov 2020
Jeje, I'm sure you've figured this out by now, but when people give you code they make up variable names that you might not have. You have to replace them with the actual variable names you used. For example, maybe you named your binary image "mask" or "BW" or "BW1" or something else. Replace binaryImage with the actual name of the binary image you used.
Jeje Ahmad
on 14 Nov 2020
you mean this one of this named:
MV = imread('cars1.png'); % To read image
MV1 = imread('backgnd.png');
or mask?
Image Analyst
on 14 Nov 2020
It counts the blobs, regardless of what they represent. You have to do better segmentation to make it count only the cars and nothing else. The Computer Vision Toolbox has car tracking capability. I don't. So look there for a solution.
Jeje Ahmad
on 23 Nov 2020
@Image Analyst
hi i am use the code to detect in video but the number of cars not give me how i can count the cars in video
foregroundDetector = vision.ForegroundDetector('NumGaussians', 3, ...
'NumTrainingFrames', 100);
videoReader = VideoReader('video.mp4');
for i = 1:200
frame = readFrame(videoReader); % read the next video frame
foreground = step(foregroundDetector, frame);
end
figure; imshow(frame); title('Video Frame');
figure; imshow(foreground); title('Foreground');
se = strel('square', 3);
filteredForeground = imopen(foreground, se);
figure; imshow(filteredForeground); title('Clean Foreground');
blobAnalysis = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
'AreaOutputPort', false, 'CentroidOutputPort', false, ...
'MinimumBlobArea', 1500);
bbox = step(blobAnalysis, filteredForeground);
result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');
numCars = size(bbox, 1);
result = insertText(result, [10 10], numCars, 'BoxOpacity', 1, ...
'FontSize', 14);
figure; imshow(result); title('Detected Cars');
videoPlayer = vision.VideoPlayer('Name', 'Detected Cars');
videoPlayer.Position(3:4) = [650,400]; % window size: [width, height]
se = strel('square', 3); % morphological filter for noise removal
while hasFrame(videoReader)
frame = readFrame(videoReader); % read the next video frame
% Detect the foreground in the current video frame
foreground = step(foregroundDetector, frame);
% Use morphological opening to remove noise in the foreground
filteredForeground = imopen(foreground, se);
% Detect the connected components with the specified minimum area, and
% compute their bounding boxes
bbox = step(blobAnalysis, filteredForeground);
% Draw bounding boxes around the detected cars
result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');
% Display the number of cars found in the video frame
numCars = size(bbox, 1);
result = insertText(result, [10 10], numCars, 'BoxOpacity', 1, ...
'FontSize', 14);
step(videoPlayer, result); % display the results
end
release(videoReader); % close the video file
See Also
Categories
Find more on Image Processing and Computer Vision in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)