知识点
像素操作之逻辑操作
- bitwise_and:逻辑与
- bitwise_xor:逻辑异或
- bitwise_or:逻辑或
上面三个类似,都是针对两张图像的位操作
python代码
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)
cv.waitKey(0)
cv.destroyAllWindows()
c++代码
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char *argv[])
{
// create image one
Mat src1 = Mat::zeros(Size(400, 400), CV_8UC3);
Rect rect(100, 100, 100, 100);
src1(rect) = Scalar(0, 0, 255);
imshow("input1", src1);
printf("create first image...\n");
// create image two
Mat src2 = Mat::zeros(Size(400, 400), CV_8UC3);
rect.x = 150;
rect.y = 150;
src2(rect) = Scalar(0, 255, 255);
imshow("input2", src2);
printf("create second image...\n");
// 逻辑操作
Mat dst1, dst2, dst3;
bitwise_and(src1, src2, dst1);
bitwise_xor(src1, src2, dst2);
bitwise_or(src1, src2, dst3);
// show results
imshow("dst1", dst1);
imshow("dst2", dst2);
imshow("dst3", dst3);
waitKey(0);
return 0;
}
运行结果如下: