我正在使用 arduino 板拍照,它返回一个十六进制字符串。我尝试过 numpy、openCV、binascii 等,但我无法像图片一样转换并保存此图像。
我收到一张“损坏的图像”,无法在我的设备上打开,但如果将其放入 RAW Pixels,我可以看到图像应有的样子。
图片的原始尺寸(arduino板上设置为QVGA 320x240)。
结果(按原始像素)是这个
这是我保存“损坏的文件”但在 rawpixels.net 中打开的实际代码
with open('img.txt') as file:
data = file.read()
data = bytes.fromhex(data[2:])
with open('image.png', 'wb') as file:
file.write(data)
您可以使用 opencv 内置函数实现您想要的目标:
import numpy as np
import cv2
with open("hex.txt") as file:
data = file.read()
buff = bytes.fromhex(data)
# Convert to 3 channel uint8 numpy array representing the BGR image
img = cv2.cvtColor(
np.frombuffer(buff, dtype=np.uint8).reshape(240, 320, 2), cv2.COLOR_BGR5652BGR
)
# Save the image to a png file
cv2.imwrite("image.png", img)
您不能仅将字节数组保存为 png 图像,文件中缺少一些标头信息。老实说,我不太熟悉 PNG 格式的详细信息,但我知道您可以通过执行以下操作轻松将十六进制值转换为 RGB:
import numpy as np
with open("hex.txt",'r') as f:
hex_str = f.read().strip()
rgb = np.array([int(hex_str[i:i+2],16) for i in range(0,len(hex_str),2)])
但是,在您提供的十六进制文件上运行此代码会产生长度为 153600 的数组,这不是预期的 320*240*3(230400) 元素,因此对于答案的其余部分,我定义了自己的十六进制字符串:
0000FF00FF000000FF00FF0000FF00FF000000FF00FF00000000FF00FF000000FF00FF0000FF00FF000000FF00FF0000
这应该创建一个 4x4 拜耳过滤器。 完整代码:
import numpy as np
import matplotlib.pyplot as plt
h=4
w=4
with open("hex.txt",'r') as f:
hex_str = f.read().strip()
rgb = np.array([int(hex_str[i:i+2],16) for i in range(0,len(hex_str),2)]).reshape(h,w,3)
plt.figure()
plt.imshow(rgb)
plt.show()
如果你想保存结果,你可以使用 plt.imsave() 生成格式正确的 PNG