返回的对象数量错误

时间:2015-10-26 20:22:15

标签: matlab image-processing

我有这个MATLab代码来计算图像中的对象数量。我选择的图像中有两个对象(汽车和骑自行车的人)。但是,程序返回错误的输出,表示有0个对象。有人可以在代码中找到错误吗?感谢。

代码背后的逻辑是:
1.给出两个输入图像,一个没有物体,一个有物体 2.将输入图像从RGB转换为灰度 3.比较两个图像并找出差异 4.将获得的图像转换为二进制 5.在图像中,仅打开面积大于4000的斑点 6.显示计数和密度。

clc;

MV = imread('car.png');                                         %To read image
MV1 = imread('backgnd.png');
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 ');
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

An empty image(of a road) with no objects(vehicles) in it
An image of the same road but with 2 objects(car and cyclist) in it

1 个答案:

答案 0 :(得分:1)

试试这将以优化方式为您提供帮助

        clc
        clear all
        close all

        im1 = imread('image1.png');
        im2 = imread('image2.png');

        gray1 = double(rgb2gray(im1));
        gray2 = double(rgb2gray(im2));

        absDif = mat2gray(abs(gray1 - gray2));

        figure,imshow(absDif,[])

        absDfbw = im2bw(absDif,0.9*graythresh(absDif));
        figure,imshow(absDfbw,[])

        absDfbw = bwareaopen(absDfbw,25);

        absDfbw = imclose(absDfbw,strel('disk',5));

        figure,imshow(absDfbw,[])

结果是:

enter image description here

谢谢