当前位置:   article > 正文

opencv两张图片作差值_opencv两张图片求差

opencv两张图片求差

第一种:

关键函数cvAbsDiff()

代码如下:

  1. #include "cv.h"
  2. #include "highgui.h"
  3. #include "cxcore.h"
  4. int main(int argc,char** argv)
  5. {cvNamedWindow("a",0);
  6.  IplImage* img=cvLoadImage("11.jpg");
  7.  cvShowImage("a",img);
  8.  cvNamedWindow("b",0);
  9.  IplImage* img1=cvLoadImage("12.jpg");
  10.  cvShowImage("b",img1);
  11.  IplImage* diff=cvCreateImage(cvGetSize(img),img->depth,img->nChannels);
  12.  cvAbsDiff(img,img1,diff);
  13.  cvNamedWindow("r",0);
  14.  cvShowImage("r",diff);
  15.  while (1)
  16.  {if (cvWaitKey(100)==27) break;
  17.  }
  18.  cvDestroyWindow("a");
  19.  cvDestroyWindow("b");
  20.  cvReleaseImage(&img);
  21.  cvReleaseImage(&img1);
  22.  cvReleaseImage(&diff);
  23.  return 0;
  24. }

第二种:

这个程序是两张图片做帧差,用C++实现的,把不同的地方用框框起来

  1. #include <iostream>
  2. #include <opencv2/opencv.hpp>
  3. using namespace std;
  4. using namespace cv;
  5. int main()
  6. {
  7. Mat currentframe, previousframe;
  8. Mat img1, img2, img3;
  9. img1 = imread("D:/1129/20006/1123120.jpg");
  10. img2 = imread("D:/1129/20006/1128120.jpg");
  11. img3 = imread("D:/1129/20006/1128120.jpg");
  12. cvtColor(img1, previousframe, CV_BGR2GRAY);
  13. cvtColor(img2, currentframe, CV_BGR2GRAY); //转化为单通道灰度图
  14. absdiff(currentframe, previousframe, currentframe);//做差求绝对值
  15. threshold(currentframe, currentframe, 130, 255.0, CV_THRESH_BINARY);
  16. dilate(currentframe, currentframe, Mat());//膨胀
  17. erode(currentframe, currentframe, Mat());//腐蚀
  18. imshow("moving area", currentframe); //显示图像
  19. vector<vector<Point> > v;
  20. vector<Vec4i> hierarchy;
  21. Mat result;
  22. Rect rect;
  23. findContours(currentframe, v, hierarchy, RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  24. for (int i = 0; i < hierarchy.size(); i++)
  25. {
  26. rect = boundingRect(v.at(i));
  27. //rect.width *= 1.5;
  28. rect.height *= 1.5;
  29. // 画最小的圆,贴着黑色
  30. //drawContours(currentframe, v, i, Scalar(0, 0, 255), 1, 8, hierarchy);
  31. // 画矩形包围圆
  32. rectangle(img3, rect, Scalar(0, 255, 0), 2);
  33. }
  34. imwrite("E:/res1.jpg", img3);
  35. imshow("moving area1", img3);
  36. //把当前帧保存作为下一次处理的前一帧
  37. //cvtColor(tempframe, previousframe, CV_BGR2GRAY);
  38. waitKey(33);
  39. system("pause");
  40. return 0;
  41. }

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号