天天看點

【OpenCV 4】圖像像素的位運算:與、或、非、異或

一、程式設計環境:

OpenCV  4.1.0
IDE Visual Studio 2017 Enterprise (15.9.13)
作業系統 Windows 10 x64 中文專業版 (1903)

二、圖像像素位運算:

  1. 與:bitwise_and()
  2. 或:bitwise_or()
  3. 非(取反):bitwise_not()
  4. 異或:bitwise_xor()

三、示例代碼:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, const char *argv[])
{
	//建立第1張矩形圖
	Mat src1 = Mat::zeros(Size(300, 300), CV_8UC3);
	Rect rect(50, 50, 100, 100);
	src1(rect) = Scalar(0, 100, 100);
	imshow("1--圖1", src1);
	

	//建立第2張矩形圖(顯示坐标與上一個錯開)
	Mat src2 = Mat::zeros(Size(300, 300), CV_8UC3);
	rect.x = 100;
	rect.y = 100;
	src2(rect) = Scalar(0, 0, 255);
	imshow("2--圖2", src2);

	//兩張圖像素邏輯操作
	Mat dst1, dst2, dst3;
	bitwise_or(src1, src2, dst1);
	bitwise_xor(src1, src2, dst2);
	bitwise_and(src1, src2, dst3);

	imshow("3--或(bitwise_or)", dst1);
	imshow("4--異或(bitwise_xor)", dst2);
	imshow("5--與(bitwise_and)", dst3);

	//使用實際圖像示範像素取反
	Mat src = imread("../images/test.png");
	namedWindow("6--原圖", WINDOW_AUTOSIZE);
	imshow("6--原圖", src);

	//取反操作
	Mat dst;
	bitwise_not(src, dst);
	imshow("7--取反(bitwise_not)", dst);

	waitKey(0);
	return 0;
}
           

四、運作效果:

【OpenCV 4】圖像像素的位運算:與、或、非、異或
【OpenCV 4】圖像像素的位運算:與、或、非、異或
【OpenCV 4】圖像像素的位運算:與、或、非、異或

繼續閱讀