opencv-007-图像像素之逻辑操作 发表于 2019-03-24 | 分类于 opencv 知识点下面三个操作类似,都是针对两张图像的位操作 bitwise_and bitwise_xor bitwise_or 针对输入图像, 图像取反操作,二值图像分析中经常用 bitwise_not 代码(c++,python)12345678910111213141516171819202122232425262728293031323334353637383940414243#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;} 1234567891011121314151617181920212223242526272829import cv2 as cvimport numpy as np# create image onesrc1 = np.zeros(shape=[400, 400, 3], dtype=np.uint8)src1[100:200, 100:200, 1] = 255src1[100:200, 100:200, 2] = 255cv.imshow("input1", src1)# create image twosrc2 = np.zeros(shape=[400, 400, 3], dtype=np.uint8)src2[150:250, 150:250, 2] = 255cv.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