[英]Construct a Numpy array from a hexadecimal string
I have a hexadecimal string "89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49"
to be specific this will contain the data of an image.我有一个十六进制字符串
"89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49"
,具体来说这将包含图像的数据。
I want to convert it to a Numpy array or possibly reconstruct an OpenCV image from the said data.我想将其转换为 Numpy 数组或可能从所述数据重建 OpenCV 图像。
The width and height will also be supplied so the dimensions of the Numpy array is known.还将提供宽度和高度,以便知道 Numpy 数组的尺寸。
How can I construct a Numpy array from the above string?如何从上述字符串构造一个 Numpy 数组?
We could use np.fromiter
, and cast the individual strings to hexadecimal, using the base
argument in int
, and then to integer type using the dtype
argument in np.fromiter
:我们可以使用
np.fromiter
,投个体线为十六进制,使用base
的说法int
使用,然后到整数类型dtype
中的说法np.fromiter
:
s = "89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49"
np.fromiter((int(x, 16) for x in s.split('-')), dtype=np.int32)
# array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73])
You can use list comprehension and the built-in int
module to convert from hexadecimal to decimal the splitted string:您可以使用列表推导和内置的
int
模块将拆分后的字符串从十六进制转换为十进制:
import numpy as np
hex_string = '89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49'
np.array([int(x, base=16) for x in hex_string.split('-')])
You can split
the string by dash and convert individual base-16 numbers into int
.您可以通过破折号
split
字符串并将单个 base-16 数字转换为int
。
>>> import numpy as np
>>> hext_str = "89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49"
>>> np.array([int(x, 16) for x in hex_str.split("-")])
array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73])
Provided that (n, m)
are dimensions of your image you can use on the result the .reshape((n, m))
method of np.array
.假设
(n, m)
是图像的尺寸可以在结果上使用.reshape((n, m))
的方法np.array
。
import numpy as np arr = np.array([int(x, 16) for x in "89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49".split("-")]) print(arr)
If memory efficiency is of concern two digits in a hexadecimal number corresponds to an unsigned 8-bit integer (ie, numbers between 0 and 255).如果关注内存效率,则十六进制数中的两位数字对应于一个无符号的 8 位整数(即 0 到 255 之间的数字)。
To return to the original string you can use format(number, '02x')
(zero padded 2-length hexadecimal number string)要返回原始字符串,您可以使用
format(number, '02x')
(零填充的 2 长度十六进制数字字符串)
hex_str = "89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49"
arr = np.fromiter((int(x, 16) for x in hex_str.split('-')), dtype=np.uint8)
# array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73],
dtype=uint8)
The array would only take up 13 bytes of space, as opposed to the default array type for integers (np.int64) which would take up 104 bytes.该数组仅占用 13 个字节的空间,而整数的默认数组类型 (np.int64) 将占用 104 个字节。
Once could return it to its original string form in the following way:曾经可以通过以下方式将其恢复为原始字符串形式:
hex_str = '-'.join((format(x, '02x') for x in arr)).upper()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.