这里Vex3f 也可以是Vec3b
#include<opencv2\opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;//读写图像,
//读写像素,
//修改像素值
int main()
{Mat src = imread("E:\\vs2015\\opencvstudy\\2.jpg", 1);if (!src.data){cout << "could not load image!" << endl;return -1;}//imshow("inputImage", src);//单通道取反Mat gray_src;cvtColor(src, gray_src, CV_BGR2GRAY);//imshow("gray_src", gray_src);int rows = gray_src.rows;int cols = gray_src.cols;Mat gray_src_invert = Mat::zeros(gray_src.size(), gray_src.type());/*for (int row = 0; row < rows; row++){for (int col = 0; col < cols; col++){int gray_pixel = gray_src.at<uchar>(row, col);gray_src_invert.at<uchar>(row, col) = 255 - gray_pixel;}}imshow("gray_src_invert", gray_src_invert);*///3通道取反Mat dst,dst2;dst.create(src.size(), src.type());dst2.create(src.size(), src.type());int height = src.rows;int width = src.cols;int nc = src.channels();for (int row = 0; row < height; row++){for (int col = 0; col < width; col++){if (nc == 1){int gray_pixel = gray_src.at<uchar>(row, col);gray_src_invert.at<uchar>(row, col) = 255 - gray_pixel;}else if (nc == 3){int b = src.at<Vec3b>(row, col)[0];int g = src.at<Vec3b>(row, col)[1];int 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;dst2.at<Vec3b>(row, col) = (r, max(g, b));}}}//imshow("3通道取反像素操作", dst);Mat bitwise_not_dst;bitwise_not(src, bitwise_not_dst); //位操作取反。等价于上面的像素操作//imshow("3通道取反bitwise_not", bitwise_not_dst);imshow("dst2", dst2);//空白图像赋值Mat M3;M3.create(gray_src.size(), gray_src.type());M3 = Scalar(0);imshow("空白图像", M3);//ROI选择Rect r(300, 300, 1000, 400); //左上角的横坐标,纵坐标,矩形高度,宽度cout << "gray_image height:" << gray_src.rows << endl;cout << "gray_image width:" << gray_src.cols << endl;Mat smallImg = gray_src(r);imshow("ROI截取图像", smallImg);waitKey(0);return 0;
}