1、像素的修改操作
c++取图像的像素:img.at操作。
读取彩色图像的像素值:
b通道: img.at(row,col)[0] ; // 表示彩色3通道,分别是b、g、r
g通道: img.at(row,col)[1] ;
r通道: img.at(row,col)[2];
示例图像:
结果图像:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char** args)
{
//读取图像
Mat img = imread("G:/testimg/img.png");
if (img.empty())
{
printf("this image cannot load");
return -1;
}
//修改像素
Mat dst;
dst.create(img.size(), img.type());
int height = img.rows;
int width = img.cols;
int nc = img.channels();
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
if (nc == 1)
{
int gray = img.at<uchar>(row, col);
dst.at<uchar>(row, col) = gray;
}
else if(nc==3)
{
int b = img.at<Vec3b>(row, col)[0];
int g = img.at<Vec3b>(row, col)[1];
int r = img.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;
}
}
}
namedWindow("output", WINDOW_AUTOSIZE);
imshow("output", dst);
waitKey(0);
return 0;
}
2、函数api:bitwise_not()
上式两个for循环进行的像素的修改,可以使用OpenCV内置函数 bitwise_not()进行替换。