一、编程环境:
OpenCV | 4.1.0 |
IDE | Visual Studio 2017 Enterprise (15.9.13) |
操作系统 | Windows 10 x64 中文专业版 (1903) |
二、图像像素读取操作:
两种方式:1、直接读取; 2、指针读取。
三、程序代码:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int artc, char** argv) {
Mat src = imread("d:/test.jpg");
if (src.empty()) {
printf("不能加载图像!\n");
return -1;
}
namedWindow("原图", WINDOW_AUTOSIZE);
imshow("原图", src);
//像素读取方式:直接读取
int height = src.rows;
int width = src.cols;
int ch = src.channels();
for (int c = 0; c < ch; c++) {
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
//判断通道
if (ch == 3) {
Vec3b bgr = src.at<Vec3b>(row, col);
bgr[0] = 255 - bgr[0];
bgr[1] = 255 - bgr[1];
bgr[2] = 255 - bgr[2];
src.at<Vec3b>(row, col) = bgr; //直接修改原图
}
else
//灰度图(只有1个通道)
if (ch == 1) {
int gray = src.at<uchar>(row, col);
src.at<uchar>(row, col) = 255 - gray;
}
}
}
}
imshow("直接读取像素图", src);
//像素读取方式:指针读取(即通过指针读取像素的方式复制原图)
Mat result = Mat::zeros(src.size(), src.type());
int blue = 0, green = 0, red = 0;
int gray;
for (int c = 0; c < ch; c++) {
for (int row = 0; row < height; row++) {
uchar* curr_row = src.ptr<uchar>(row);
uchar* result_row = result.ptr<uchar>(row);
for (int col = 0; col < width; col++) {
//判断通道
if (ch == 3) {
//从src中读取像素值
blue = *curr_row++;
green = *curr_row++;
red = *curr_row++;
//写入result中(写入位置与src一一对应)
*result_row++ = blue;
*result_row++ = green;
*result_row++ = red;
}
else
//灰度图(只有1个通道)
if (ch == 1) {
gray = *curr_row++;
*result_row++ = gray;
}
}
}
}
imshow("指针读取像素图", result);
waitKey(0);
return 0;
}