OpenCV学习(C++)——像素点的读取
C++中的像素遍历与访问
对彩色图片处理:(原像素-255)反色 基于数组下表改变每一个像素点
数组遍历
void QuickDemo::pixel_visit_demo(Mat &image)
{
int w = image.cols;//获取图像宽度
int h = image.rows;//获取图像高度
int dims = image.channels();//获取通道数
for (int row = 0; row < h; row++)
{
for (int col = 0; col < w; col++)
{
if (dims == 1)//灰度图像
{
int pv = image.at<uchar>(row, col);//单通道 像素值是uchar型
image.at<uchar>(row, col) = 255 - pv;
}
if (dims == 3)//彩色图像
{
Vec3b bgr=image.at<Vec3b>(row, col);//返回三个值哦 可以把bgr这个结构看成数组
image.at<Vec3b>(row, col)[0] = 255 - bgr[0];
image.at<Vec3b>(row, col)[1] = 255 - bgr[1];
image.at<Vec3b>(row, col)[2] = 255 - bgr[2];
}
}
}
imshow("像素读写演示", image);
}
指针方式遍历
把上面的代码中的双重for循环改成下main这个就行了
for (int row = 0; row < h; row++)
{
uchar *current_row = image.ptr<uchar>(row);
for (int col = 0; col < w; col++)
{
if (dims == 1)
{
int pv = *current_row;
*current_row++ = 255 - pv;
}
if (dims == 3)
{
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
}
}
}
记得自己定义void QuickDemo::pixel_visit_demo(Mat &image);这个函数
主函数
#include<opencv2/opencv.hpp>
#include<iostream>
#include<quickjopencv.h>
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("C:/Users/LENOVO/Desktop/work/picture/2.png");
if (src.empty())
{
printf("could not find picture!\n");
return -1;
}
imshow("输入窗口", src);
QuickDemo qd;
qd.pixel_visit_demo(src);
waitKey(0);
destroyAllWindows();
return 0;
}
|