使用 OpenCV 读写 RGB 文件

Reading and writing RGB files using OpenCV

python 和 OpenCV 的新手。我正在使用 OpenCV 读取 jpg,然后将其作为十六进制数据写入文件,我再次读取文件并构建一个 numpy 数组并使用 imshow 显示图像,但它看起来与原始图像不同。为什么图像颜色变蓝了?

file1.py:

import cv2
import numpy as np

img = cv2.imread('D:\cat.jpg')

cv2.imshow('img', img)     #Shows the image
cv2.waitKey(3000)

with open('D:\catHex', 'wb') as f:
    f.write(img)
    f.close()

file2.py:

import cv2
import numpy as np

img = np.zeros((640,640,3), np.uint8)
row = 0
col = 0

with open('D:\catHex', 'rb') as f:

    while(row < 640):

        img[row,col,2] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,0] = ord(f.read(1))

        col = col + 1
        if(col == 640):
            col = 0
            row = row + 1

    cv2.imshow('img',img)
    cv2.waitKey(3000)

您在第二个脚本中读取图像时交换了红色和蓝色通道,因此图像看起来是蓝色的。以下应按预期工作:

img[row,col,0] = ord(f.read(1))
img[row,col,1] = ord(f.read(1))
img[row,col,2] = ord(f.read(1))

你也可以用下面更像 python 的方式写你的 while 循环 for-loops:

for row in range(640):
    for col in range(640):
        img[row,col,0] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,2] = ord(f.read(1))

    cv2.imshow('img',img)
    cv2.waitKey(3000)