阿牧路泽

哪有那么多坚强,无非是死扛罢了
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

9、【opencv入门】基本图像运算--加减与或

Posted on 2018-09-17 16:07  阿牧路泽  阅读(662)  评论(0编辑  收藏  举报

一、图像加法

【示例】

 1 //图像的加法
 2 #include<opencv2/opencv.hpp>
 3 #include<iostream>
 4 
 5 using namespace cv;
 6 using namespace std;
 7 
 8 int main(){
 9     Mat img1=imread("1.jpg");
10     Mat img2=imread("2.jpg");
11     Mat dst;//存储结果
12     imshow("img1",img1);
13     imshow("img2",img2);
14 
15     cout<<"img1  "<<int(img1.at<Vec3b>(10,10)[0])<<endl;//img1在坐标(10,10)的蓝色通道的值,强制转成int
16     cout<<"img2  "<<int(img2.at<Vec3b>(10,10)[0])<<endl;
17 
18     dst=img1+img2;//这两个加法效果相同
19     //add(img1,img2,dst);//注意:这两个加法要求被加的图片尺寸必须一致
20     //addWeighted(img1,0.5,img2,0.5,0,dst);//按权重相加,下一行dst输出参数为正常参数的一半
21     cout<<"dst  "<<int(dst.at<Vec3b>(10,10)[0])<<endl;
22     imshow("dst",dst);
23     waitKey(0);
24 }

  通过打印两幅图像(10, 10)处蓝色通道的值,我们可以看到,dst在(10,10)处蓝色通道的值等于img1和img2在该处的值的和。

二、图像的减法

【示例】

 1 //图像的减法
 2 #include<opencv2/opencv.hpp>
 3 #include<iostream>
 4 using namespace cv;
 5 using namespace std;
 6 
 7 int main(){
 8     Mat img1=imread("1.jpg");
 9     Mat img2=imread("2.jpg");
10     Mat dst;//存储结果
11     imshow("img1",img1);
12     imshow("img2",img2);
13 
14     cout<<"img1  "<<int(img1.at<Vec3b>(10,10)[1])<<endl;//img1在坐标(10,10)的蓝色通道的值,强制转成int
15     cout<<"img2  "<<int(img2.at<Vec3b>(10,10)[1])<<endl;
16 
17     //dst=img1-img2;//这两个减法效果相同    若dst<0,则dst=0
18     //subtract(img1,img2,dst);//注意:要求被处理图片尺寸一致
19     absdiff(img1,img2,dst);//若dst<0,则dst=|dst|>=0    用于检测两幅相似图像的不同点,效果比上面的两种减法好
20     cout<<"dst  "<<int(dst.at<Vec3b>(10,10)[1])<<endl;
21     imshow("dst",dst);
22     waitKey(0);
23     return 0;
24 }

  通过打印两幅图像(10, 10)处绿色通道的值,我们可以看到,dst在(10,10)处绿色通道的值等于img1和img2在该处的值的差。

 三、乘除与或非

1     dst=5*img1;//增加曝光
2     dst=img1/5;//降低曝光
3     bitwise_and(img1,img2,dst);//逻辑与,求交集
4     bitwise_or(img1,img2,dst);//逻辑或,求并集
5     bitwise_not(img1,dst);//逻辑非,求补集
6     bitwise_xor(img1,img2,dst);//异或,相同为0,相异为1