이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
code to detection the cars this code not counting cars properly How do i make it count correct ?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
KSSV
2020년 10월 18일
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
Jeje Ahmad
2020년 10월 22일
can you help me the code does not count correct ; what is the value i will change to count correct ?
please
@KSSV
KSSV
2020년 10월 24일
추가 답변 (1개)
Image Analyst
2020년 10월 24일
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
Jeje Ahmad
2020년 10월 26일
i try it but give error
Undefined function or variable 'xline'.
Error in new (line 47)
xline(thresh, 'LineWidth', 2);
Image Analyst
2020년 10월 26일
You have an old version. Try replacing xline with line:
line([thresh, thresh], ylim, 'LineWidth', 2);
Jeje Ahmad
2020년 10월 26일
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
2020년 10월 26일
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
2020년 10월 27일
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
2020년 10월 28일
편집: Image Analyst
2020년 10월 28일
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
2020년 10월 28일
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
2020년 10월 28일
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
2020년 10월 29일
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
2020년 10월 30일
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
2020년 11월 12일
hi i am using this function but give me error
how i can correct this error
@Image Analyst
Jeje Ahmad
2020년 11월 12일
Undefined function or variable 'Call'.
Error in new1 (line 78)
Call bwlabel()
Image Analyst
2020년 11월 12일
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
2020년 11월 13일
yes i see
but give me this error
Undefined function or variable 'binaryImage'.
Error in new (line 69)
[labeledImage, numberOfCars] = bwlabel(binaryImage);
Image Analyst
2020년 11월 14일
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
2020년 11월 14일
you mean this one of this named:
MV = imread('cars1.png'); % To read image
MV1 = imread('backgnd.png');
or mask?
Image Analyst
2020년 11월 14일
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
2020년 11월 23일
@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
참고 항목
카테고리
Help Center 및 File Exchange에서 Image Processing and Computer Vision에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- 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)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)