#include <opencv2/opencv.hpp> #include <iostream> #include <math.h> using namespace cv; using namespace std; int main() { Mat src; //原图 src = imread(".//pic//test.jpg",IMREAD_UNCHANGED); if (src.empty()) { cout << "can not load image" << endl; return -1; } namedWindow("input", CV_WINDOW_AUTOSIZE); imshow("input", src); //单通道图像反色处理 Mat gray_src; cvtColor(src, gray_src, CV_BGR2GRAY); namedWindow("input", CV_WINDOW_AUTOSIZE); imshow("output", gray_src); int height = gray_src.rows; int width = gray_src.cols; /*for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { int gray = gray_src.at<uchar>(row, col); gray_src.at<uchar>(row, col) = 255 - gray; } } imshow("反色", gray_src);*/ //三通道图像的反色 Mat dst; dst.create(src.size(), src.type()); height = src.rows; width = src.cols; int nc = src.channels(); //b,g,r 三通道 int b; int g; int r; /*for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { b = src.at<Vec3b>(row, col)[0]; g= src.at<Vec3b>(row, col)[1]; r = src.at<Vec3b>(row, col)[2]; dst.at<Vec3b>(row, col)[0] = 255 - b; dst.at<Vec3b>(row, col)[1] = 255 - g; dst.at<Vec3b>(row, col)[2] = 255 - r; } }*/ //api函数 //bitwise_not(src, dst); //只保留红色通道的值 for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { b = src.at<Vec3b>(row, col)[0]; g = src.at<Vec3b>(row, col)[1]; r = src.at<Vec3b>(row, col)[2]; dst.at<Vec3b>(row, col)[0] = 0; dst.at<Vec3b>(row, col)[1] = 0; dst.at<Vec3b>(row, col)[2] = r; } } imshow("三通道反色", dst); waitKey(0); return 0; }