用Python将图像转换为十六进制数据 [英] Image to Hexidecimal Data Conversion in Python

查看:149
本文介绍了用Python将图像转换为十六进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python,我正在尝试将黑白图像的每个像素转换为十六进制,并将其存储在".txt"文件中.我必须为我的应用程序使用C,以便它更容易从文本文件中读取,然后在C代码中进行整个转换.我已经从网上调整了一些示例代码,但是我对使用Python还是不太有经验.

Using Python I am trying to convert each pixel of a B/W image to hex and store it in a '.txt' file. I have to use C for my application so its easier to read from a text file then do the entire conversion in C code. I have tweaked some example code from online, but I am still not very experienced with using Python.

当我运行python脚本时,它仅生成两个十六进制值,而不是八个.起初我以为是黑白图像,但是RGB图像的黑色应该包含 0x000000 ,白色应该包含 0xFFFFFF .

When I run my python script it only produces two hex values instead of eight. At first I thought this was from the image being B/W, but an RGB image should contain 0x000000 for black and 0xFFFFFF for white.

Python脚本

from binascii import hexlify
import re

hexValNew = ''
placeHolder ='0'

file = open('Frame2.txt', 'w') #Create txt file for data

with open('Frame2.png', 'rb') as f:
    binVal = f.read(1)
    while len(binVal) != 0:
        hexVal = hex(ord(binVal))
        hexValNew = hexVal[2:4] #Remove "0x" from hex() process
        hexValString = str(hexValNew)

        if len(hexValString) == 1:
            hexValString = placeHolder + hexValString
        print hexVal

        #print(hexValString) #Test Line
        file.write(hexValString) #Write adjusted hex value to txt file
        binVal = f.read(1)

file.close() #Close txt file

./a.out部分

ff00622600c4a2d7c290000049454e44e426082

ff 00 62 26 e0 c4 a2 d7 c2 90 00 00 49 45 4e 44 ae 42 60 82

据我了解,该值应该是返回的八位数字,而不仅仅是两位.

From what I understand, the value should be have eight digits returned and not just two.

推荐答案

在Unix上的ImageMagick中,您可以执行以下操作:

In ImageMagick on Unix, you can do the following:

convert rose.png:[5x5] txt: | tail -n +2 | sed 's/[ ][ ]*/ /g' | awk '{print $1,$3}'
0,0: #414042
1,0: #634040
2,0: #B53D30
3,0: #A54845
4,0: #998886
0,1: #6A6674
1,1: #C0494A
2,1: #E4312B
3,1: #DB403F
4,1: #98936E
0,2: #77796F
1,2: #CA948B
2,2: #A94D43
3,2: #603D31
4,2: #405937


格式为列,行:十六进制.


The format is column,row: hex.

您可以根据需要将其重定向到文件.我不是Windows用户.但是Windows可能有与Unix命令等效的Windows.如果不是,则可以解析txt:的输出.参见 https://imagemagick.org/Usage/files/#txt

You can redirect that to a file if you want. I am not a Windows users. But there are likely Windows equivalents of the Unix commands. If not, then you can parse the output from the txt:. See https://imagemagick.org/Usage/files/#txt

这篇关于用Python将图像转换为十六进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆