使用 Python OpenCV 读取 JPG 彩色图像并将图像保存为原始或二进制文件

Reading JPG colored image and saving image into raw or binary file using Python OpenCV

我正在尝试读取 JPG 图像并想将其保存在二进制原始图像文件中。输出应该是平面形式,比如第一个红色通道等等。 到目前为止,我制作的这段代码没有用。你能建议我该怎么做吗?

import cv2
H = 512;
W = 512;
size = H*W;

img = cv2.imread('f.jpg')
img = cv2.resize(img, (H, W))
name = 'f'+str(H)+'x'+str(W)+'.bin'
f = open(name, 'w+b')
binary_format = bytearray(img)
f.write(binary_format)
f.close()

你可以这样做:

#!/usr/bin/env python3

import cv2
import numpy as np

# Output dimensions
H, W = 512, 512

# Open image and resize to 512x512
img = cv2.imread('image.jpg')
img = cv2.resize(img, (H, W))

# Save as planar RGB output file
name = f'f-{H}x{W}.bin'
with open(name, 'w+b') as f:
    f.write(img[...,2].copy())     # write Red channel
    f.write(img[...,1].copy())     # write Green channel
    f.write(img[...,0].copy())     # write Blue channel

我把.copy()放在那里是为了让数据连续写入。我先写通道 2,然后是 1,然后是 0,因为 OpenCVBGR 顺序存储图像,我假设你首先想要红色平面。


请注意,您可以在终端中使用 ImageMagick 执行上述操作而无需任何代码:

magick input.jpg -resize 512x512 -interlace plane -depth 8 RGB:data.bin

如果您愿意将图像的宽高比扭曲为指定尺寸,请将上面的 512x512 更改为 512x512\!

从二进制平面交错 RGB 数据创建 JPEG 的逆过程是:

magick -size 512x512 -depth 8 -interlace plane RGB:data.bin reconstituted.jpg