一、逻辑运算(and, or, xor, not)
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("colors.jpg");
if (img.empty()) {
cout << "读取图片失败" << endl;
return -1;
}
//创建两个黑白图像
Mat img0 = Mat::zeros(200, 200, CV_8UC1); //200*200和8位无符号黑色单通道图像
Mat img1 = Mat::zeros(200, 200, CV_8UC1);
Rect rect0(50, 50, 100, 100);
img0(rect0) = Scalar(255); // 圈定一小块区域用白色标记
Rect rect1(100, 100, 100, 100);
img1(rect1) = Scalar(255);
imshow("img0", img0);
imshow("img1", img1);
//进行逻辑运算
Mat test_and, test_or, test_xor, test_not, test_imgNot;
bitwise_not(img0, test_not);
bitwise_and(img0, img1, test_and);
bitwise_or(img0, img1, test_or);
bitwise_xor(img0, img1, test_xor);
bitwise_not(img, test_imgNot);
//展示逻辑运算的结果
imshow("test_not", test_not);
imshow("test_and", test_and);
imshow("test_or", test_or);
imshow("test_xor", test_xor);
imshow("test_not", test_not);
imshow("test_imgNot", test_imgNot);
waitKey(0);
return 0;
}
二、图像二值化
#include<opencv2/opencv.hpp>
#include<iostream>
#include<vector>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("colors.jpg");
if (img.empty()) {
cout << "图片读取失败" << endl;
}
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY); //将RGB图像img转为灰度图gray
// 彩图BINARY二值化
Mat binary, binary_inv;
threshold(img, binary, 125, 255, THRESH_BINARY);
threshold(img, binary_inv, 125, 255, THRESH_BINARY_INV);
imshow("binary", binary);
imshow("binary_inv", binary_inv);
//灰度图BINARY二值化
Mat binary_gray, binary_gray_inv;
threshold(gray, binary_gray, 125, 255,THRESH_BINARY);
threshold(gray, binary_gray_inv,125, 255, THRESH_BINARY_INV);
imshow("binary_gray", binary_gray);
imshow("binary_gray_inv", binary_gray_inv);
//灰度图TOZERO二值化
Mat tozero_gray, tozero_gray_inv;
threshold(gray, tozero_gray, 125, 255, THRESH_TOZERO);
threshold(gray, tozero_gray_inv, 125, 255, THRESH_TOZERO_INV);
imshow("tozero_gray", binary_gray);
imshow("tozero_gray_inv", binary_gray_inv);
//灰度图TRUNC二值化
Mat trunc_gray;
threshold(gray, trunc_gray, 125, 255, THRESH_TRUNC);
imshow("trunc_gray", trunc_gray);
Mat gray_thr = imread("colors.jpg", IMREAD_GRAYSCALE);
//灰度图OSTU二值化
Mat otsu_gray;
threshold(gray_thr, otsu_gray, 100, 255,THRESH_BINARY | THRESH_OTSU);
imshow("trunc_gray", otsu_gray);
//灰度图triangle二值化
Mat triangle_gray;
threshold(gray_thr, triangle_gray, 100, 255, THRESH_BINARY | THRESH_TRIANGLE);
imshow("triangle_gray", triangle_gray);
//灰度图自适应二值化
Mat adapt_mean_gray;
adaptiveThreshold(gray_thr, adapt_mean_gray, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 55, 0);
imshow("adapt_mean_gray", adapt_mean_gray);
Mat adapt_gauss_gray;
adaptiveThreshold(gray_thr, adapt_gauss_gray, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 55, 0);
imshow("adapt_gauss_gray", adapt_gauss_gray);
waitKey(0);
return 0;
}
参考资料:
《OpenCV4快速入门》