1.对一张图片中所有像素点取反
2.头文件
#pragma once
#include<opencv2/opencv.hpp>
using namespace cv;
class QuickDemo
{
public:
//void color(Mat& src);//转换函数
//void color_creat();//创建空白函数
void visit_demo(Mat &image);//访问像素点
};
3.quick.cpp
3.1像素点遍历
void QuickDemo::visit_demo(Mat &image)
{
int w = image.cols;
int h = image.rows;
int dim = image.channels();
for (int col=0; col< w; col++)
{
for (int row=0; row < h; row++)
{
if (dim == 1)
{
int pv = image.at<uchar>(row, col);
image.at<uchar>(row, col) = 255 - pv;
}
if (dim == 3)
{
Vec3b pv = image.at<Vec3b>(row, col);
image.at<Vec3b>(row, col)[0] = 255 - pv[0];
image.at<Vec3b>(row, col)[1] = 255 - pv[1];
image.at<Vec3b>(row, col)[2] = 255 - pv[2];
}
}
}
imshow("显示图像", image);
}
3.2指针遍历
void QuickDemo::visit_demo(Mat &image)
{
int w = image.cols;
int h = image.rows;
int dim = image.channels();
for (int row = 0; row < h; row++)
{
uchar* rows_ptr = image.ptr<uchar>(row);
for (int col = 0; col < w; col++)
{
if (dim == 0)
{
*rows_ptr++ = 255 - *rows_ptr;
}
if (dim == 3)
{
*rows_ptr++ = 255 - *rows_ptr;
*rows_ptr++ = 255 - *rows_ptr;
*rows_ptr++ = 255 - *rows_ptr;
}
}
}
imshow("显示图像", image);
}
其中
uchar* rows_ptr = image.ptr<uchar>(row);为定义Mat一行的指针
*rows_ptr++为一行第一个数到一行第二个数
4.main函数
int main()
{
Mat src;
QuickDemo test;
src = imread("D:/Luban/cv/2.jpg");
//test.color(src);
//test.color_creat();
test.visit_demo(src);
waitKey(0);
}
5.成果展示