1.对灰度图像的像素操作:
#include<iostream> #include<opencv2/opencv.hpp> using namespace std; using namespace cv; int main(int argc, char **argv) { Mat src = imread("D:/meinv.jpg"); namedWindow("源图像",CV_WINDOW_AUTOSIZE); imshow("源图像",src); /*Mat gray; cvtColor(src, gray, CV_BGR2GRAY); imshow("灰度图像", gray);*/ /* 对灰度图像的像素改写 int height = src.rows; int width = src.cols; int channels = src.channels(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int gray_data = gray.at<uchar>(i, j); gray.at<uchar>(i, j) = 255 - gray_data; } } imshow("反色图像", gray);*/ }
显示结果:
(1)彩色图像
(2)灰度图像
(3)反色图像
2.对彩色图像像素的操作
Mat dst; dst.create(src.size(), src.type()); int height = src.rows; int width = src.cols; int channels = src.channels(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int b = src.at<Vec3b>(i, j)[0]; int g = src.at<Vec3b>(i, j)[1]; int r = src.at<Vec3b>(i, j)[2]; dst.at<Vec3b>(i, j)[0] = 255 - b; dst.at<Vec3b>(i, j)[1] = 255 - g; dst.at<Vec3b>(i, j)[2] = 255 - r; } } //进行反色的另一种方法:调用API /*bitwise_not(src, dst);*/ imshow("反色图像",dst); imwrite("D:/dst.jpg", dst); waitKey(0); return 0;
显示结果: