opencv-007-图像像素之逻辑操作

知识点

下面三个操作类似,都是针对两张图像的位操作

  • bitwise_and
  • bitwise_xor
  • bitwise_or

针对输入图像, 图像取反操作,二值图像分析中经常用

  • bitwise_not

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 图像像素的逻辑操作
*/
int main() {
// create image one, CV_8UC3创建三通道图像
Mat src1 = Mat::zeros(Size(400, 400), CV_8UC3);
Rect rect(100,100,100,100);
// Scalar() 参数为BGR三通道值,绿色和红色加起来是黄色
src1(rect) = Scalar(0, 255, 255);
imshow("input1", src1);

// create image two
Mat src2 = Mat::zeros(Size(400, 400), CV_8UC3);
rect.x = 150;
rect.y = 150;
src2(rect) = Scalar(0, 0, 255);
imshow("input2", src2);

// 逻辑操作
Mat dst1, dst2, dst3;
bitwise_and(src1, src2, dst1);
bitwise_xor(src1, src2, dst2);
bitwise_or(src1, src2, dst3);
imshow("and", dst1);
imshow("xor", dst2);
imshow("or", dst3);

// 演示取反操作
Mat src = imread("../images/test1.jpg");
Mat dst;
imshow("input", src);
bitwise_not(src,dst);
imshow("not", dst);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import cv2 as cv
import numpy as np

# create image one
src1 = np.zeros(shape=[400, 400, 3], dtype=np.uint8)
src1[100:200, 100:200, 1] = 255
src1[100:200, 100:200, 2] = 255
cv.imshow("input1", src1)
# create image two
src2 = np.zeros(shape=[400, 400, 3], dtype=np.uint8)
src2[150:250, 150:250, 2] = 255
cv.imshow("input2", src2)

dst1 = cv.bitwise_and(src1, src2)
dst2 = cv.bitwise_xor(src1, src2)
dst3 = cv.bitwise_or(src1, src2)

cv.imshow("dst1", dst1)
cv.imshow("dst2", dst2)
cv.imshow("dst3", dst3)

src = cv.imread("../images/test1.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
dst = cv.bitwise_not(src)
cv.imshow("dst", dst)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github