I am trying to find the difference between 2 images using Opencv. The code is given below:
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include<iostream>
int main()
{
char a,b;
cv::Mat frame;
cv::Mat frame2;
VideoCapture cap(0);
if(!cap.isOpened())
{
cout<<"Camera is not connected"<<endl;
getchar();
exit(0);
}
Mat edges;
namedWindow("Camera Feed",1);
cout<<"Ready for background?(y/Y)"<<endl;
cin>>a;
if(a=='y'||a=='Y')
{
cap>>frame;
cv::cvtColor(frame,frame,CV_RGB2GRAY);
cv::GaussianBlur(frame,frame,cv::Size(3,3),2.00,0,BORDER_DEFAULT);
}
cout<<"Ready for foreground?(y/Y)"<<endl;
cin>>b;
if(b=='y'||b=='Y')
{
cap>>frame2;
cv::cvtColor(frame2,frame2,CV_RGB2GRAY);
cv::GaussianBlur(frame2,frame2,cv::Size(3,3),2.00,0,BORDER_DEFAULT);
}
cv::absdiff(frame,frame2,frame);
imwrite("img_bw.jpg",frame);
return 0;
}
The code is running fine but the output is not completely black and white like I want. Where am I going wrong?
The code you’ve given will output shades of gray corresponding to the difference of individual pixels between the two images. There will always be some small difference even between elements which haven’t changed, just because of the noise or variability of the camera sensor. If you need purely black and white, you need to select a threshold where the differences are significant and convert every pixel below that threshold to 0, and everything above the threshold to 255.