opencv-004-图像像素读写操作

知识点

  1. C++中的像素遍历与访问
    • 数组遍历
    • 指针方式遍历
  2. Python中的像素遍历与访问
    • 数组遍历

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

/**
* 读取图像,实现像素反转
*/
int main() {
Mat src = imread("../images/liuyifei_1.png");
Mat src_copy = src.clone();
int height = src.rows;
int width = src.cols;
int ch = src.channels();
imshow("input", src);

// 直接读取图像像素
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 if (ch == 1) {
int gray = src.at<uchar>(row, col);
src.at<uchar>(row, col) = 255 - gray;
}
}
}
imshow("output1", src);

// 指针读取
Mat result = Mat::zeros(src_copy.size(), src_copy.type());
int blue = 0, green = 0, red = 0;
int gray;
for (int row = 0; row < height; ++row) {
// curr_row为第row行的首地址,遍历时,前三个字节表示的是第一个像素的BGR值,
// 注意BGR值顺序,接下来三个字节是第二个像素的值。
uchar *curr_row = src_copy.ptr<uchar>(row);
uchar *result_row = result.ptr<uchar>(row);
for (int col = 0; col < width; ++col) {
if (ch == 3) {
blue = *curr_row++;
green = *curr_row++;
red = *curr_row++;

*result_row++ = 255 - blue;
*result_row++ = 255 - green;
*result_row++ = 255 - red;
} else if (ch == 1) {
gray = *curr_row++;
*result_row++ = gray;
}
}
}

imshow("output2", result);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import cv2 as cv

src = cv.imread("../images/liuyifei_1.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
h, w, ch = src.shape
print("h , w, ch", h, w, ch)
for row in range(h):
for col in range(w):
b, g, r = src[row, col]
b = 255 - b
g = 255 - g
r = 255 - r
src[row, col] = [b, g, r]
cv.imshow("output", src)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github