使用 Hexademicals 将图像文件转换为文本文件

Turning image file into text file with Hexademicals

你好,我正在尝试使用 Python 做学校项目,但我遇到了困难,所以我需要一些帮助。 我正在尝试导入图像并读取它并导出十六进制文本文件。

例如我用 MS Paint 制作的这张图片

让我们假设这是一张 9 像素的图像。我想导入此图像并将其转换为文本文件,内容类似于

FF0000 0000FF 00FF00
0000FF FF0000 00FF00
00FF00 FF0000 0000FF

使用 Python 可以吗?或者我需要另一种编程语言来做吗? 提前谢谢大家!(对不起,如果我的英语不好)

opencv 无法读取图像简化。

import cv2

img = cv2.imread('image.png')
print(img.shape)

cy=img.shape[0]
cx=img.shape[1]
f = open('img.txt', 'w')
for row in img:
    for col in row:
        str="%02x%02x%02x"%(col[0], col[1], col[2])
        f.write(str)
f.close()

你可以在 command-line 上完成,不需要 Python,使用 ImageMagick,它安装在大多数 Linux 发行版上,并且适用于 macOS 和 Windows.

它适用于 PNG、JPEG 和大约 200 种其他图像类型。让我们制作一个示例图像:

convert xc:red  xc:blue xc:lime +append    \
     \( xc:blue xc:red  xc:lime +append \) \
     \( xc:lime xc:red  xc:blue +append \) \
     -append start.png

让我们把它放大,这样你就可以看到了(我本来可以一次完成的):

convert start.png -scale 400x start.png

现在回答你的问题,我可以将其转换为原始 RGB(通过解释所有图像大小、调色板、压缩和 headers)并通过 xxd 进行十六进制格式处理:

convert start.png -depth 8 rgb: | xxd -g3 -c9 -u
00000000: FF0000 0000FF 00FF00  .........
00000009: 0000FF FF0000 00FF00  .........
00000012: 00FF00 FF0000 0000FF  .........

如果你想去掉前面的地址和后面的点,你可以使用:

convert start.png -depth 8 rgb: | xxd -g3 -c9 -u | sed 's/  .*//; s/^.*: //'
FF0000 0000FF 00FF00
0000FF FF0000 00FF00
00FF00 FF0000 0000FF

sed 命令说..."Anywhere you see two spaces, remove them and all that follows. Remove anything up to and including a colon followed by a space.".

或者普通转储更好:

convert start.png -depth 8 rgb: | xxd -g3 -c9 -u -p
FF00000000FF00FF00
0000FFFF000000FF00
00FF00FF00000000FF

注意:如果使用 ImageMagick v7+,请将上述所有示例中的 convert 替换为 magick

我真的不会说 Python,但我已经尝试学习了一些,这似乎可以满足您的要求。我可能不是很Pythonic,但至少它只使用PIL,它比OpenCV小很多而且更容易安装!

#!/usr/local/bin/python3
import sys
from PIL import Image

# Check image supplied as argument
if len(sys.argv)!=2:
    sys.exit("ERROR: Please specify a file")

# Load image
img=Image.open(sys.argv[1])

# Retrieve dimensions
w,h=img.size

# Make RGB if palettised
if img.mode=="P":
    img=img.convert('RGB')

p=img.load()
for y in range(0,h):
    for x in range(0,w):
        r,g,b=p[x,y]
        str="%02x%02x%02x "%(r,g,b)
        print(str,end='')
    print()