通过数组遍历方式来实现图像像素读写操作
需要注意三通道的数据类型 – image.at(row, col)
04_opencv_mat.h
#pragma once
#ifndef _OPENCV_MAT_H
#define _OPENCV_MAT_H
#include <opencv2/opencv.hpp>
using namespace cv;
class QuickDemo {
public:
void pixel_visit_demo(Mat& image);
};
#endif
04_opencv_mat.cpp
#include <iostream>
#include "04_opencv_mat.h"
using namespace std;
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)
{
uchar pv = image.at<uchar>(row,col);
image.at<uchar>(row, col) = 255 - pv;
}
if (dims == 3)
{
Vec3b bgr = image.at<Vec3b>(row, col);
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);
}
输出和输入图像如下图所示。
|