时间:2021-07-20 08:54:49 | 栏目:C代码 | 点击:次
本文为大家分享了使用opencv处理两张图片帧差的具体代码,供大家参考,具体内容如下
这个程序是两张图片做帧差,用C++实现的,把不同的地方用框框起来,仔细读一下程序,应该还是蛮简单的哈哈,opencv处理图片的基础。
opencv配置不用我说了吧,源码cmake编译,然后导入vs即可。
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main() { Mat currentframe, previousframe; Mat img1, img2, img3; img1 = imread("D:/1129/20006/1123120.jpg"); img2 = imread("D:/1129/20006/1128120.jpg"); img3 = imread("D:/1129/20006/1128120.jpg"); cvtColor(img1, previousframe, CV_BGR2GRAY); cvtColor(img2, currentframe, CV_BGR2GRAY); //转化为单通道灰度图 absdiff(currentframe, previousframe, currentframe);//做差求绝对值 threshold(currentframe, currentframe, 130, 255.0, CV_THRESH_BINARY); dilate(currentframe, currentframe, Mat());//膨胀 erode(currentframe, currentframe, Mat());//腐蚀 imshow("moving area", currentframe); //显示图像 vector<vector<Point> > v; vector<Vec4i> hierarchy; Mat result; Rect rect; findContours(currentframe, v, hierarchy, RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); for (int i = 0; i < hierarchy.size(); i++) { rect = boundingRect(v.at(i)); //rect.width *= 1.5; rect.height *= 1.5; // 画最小的圆,贴着黑色 //drawContours(currentframe, v, i, Scalar(0, 0, 255), 1, 8, hierarchy); // 画矩形包围圆 rectangle(img3, rect, Scalar(0, 255, 0), 2); } imwrite("E:/res1.jpg", img3); imshow("moving area1", img3); //把当前帧保存作为下一次处理的前一帧 //cvtColor(tempframe, previousframe, CV_BGR2GRAY); waitKey(33); system("pause"); return 0; }