簡體   English   中英

從一個十六進制字符串構造一個 Numpy 數組

[英]Construct a Numpy array from a hexadecimal string

我有一個十六進制字符串"89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49" ,具體來說這將包含圖像的數據。

我想將其轉換為 Numpy 數組或可能從所述數據重建 OpenCV 圖像。

還將提供寬度和高度,以便知道 Numpy 數組的尺寸。

如何從上述字符串構造一個 Numpy 數組?

我們可以使用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])

您可以使用列表推導和內置的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('-')])

您可以通過破折號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])

假設(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)

如果關注內存效率,則十六進制數中的兩位數字對應於一個無符號的 8 位整數(即 0 到 255 之間的數字)。

要返回原始字符串,您可以使用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)

該數組僅占用 13 個字節的空間,而整數的默認數組類型 (np.int64) 將占用 104 個字節。

曾經可以通過以下方式將其恢復為原始字符串形式:

hex_str = '-'.join((format(x, '02x') for x in arr)).upper()

使用 ctypes 從 C 結構構造 numpy 數組。 值錯誤:' <p' is not a valid pep 3118 buffer format string< div><div id="text_translate"><p> 考慮以下代碼:</p><p> by_ref.h</p><pre> typedef struct OutPutImage{ double *** output_img; int nb_images; int nb_cols; int nb_rows; }opi_; void test_output_images(struct OutPutImage * out, int nb_images, int nb_cols, int nb_rows);</pre><p> by_ref.c</p><pre> #include &lt;stdlib.h&gt; #include "by_ref.h" void test_output_images(struct OutPutImage* out, int nb_images, int nb_cols, int nb_rows){ out-&gt;nb_images = nb_images; out-&gt;nb_cols = nb_cols; out-&gt;nb_rows = nb_rows; out-&gt;output_img = (double***)malloc((nb_images) * sizeof(double**)); for(int i = 0; i &lt; nb_images; i++){ out-&gt;output_img[i] = (double**)malloc((nb_cols) * sizeof(double*)); for(int j = 0; j &lt; nb_cols; j++){ out-&gt;output_img[i][j] = (double*)malloc((nb_rows) * sizeof(double)); for(int k = 0; k &lt; nb_rows; k++){ out-&gt;output_img[i][j][k] = 0; } } } }</pre><p> 和</p><p> by_ref.py</p><pre> import ctypes import numpy.ctypeslib as npct import numpy as np class OutPutImage(ctypes.Structure): _fields_ = [('output_img', npct.ndpointer(dtype=np.double, ndim=3)), ('nb_images', ctypes.c_int), ('nb_cols', ctypes.c_int), ('nb_rows', ctypes.c_int)] _libc = ctypes.CDLL("./by_ref.so") def __init__(self, nb_images=None, nb_cols=None, nb_rows=None): self.nb_images = nb_images self.nb_cols = nb_cols self.nb_rows = nb_rows if __name__ == '__main__': libc_adm = ctypes.CDLL("./by_ref.so") libc_adm.test_output_images.restype = ctypes.c_int libc_adm.test_output_images.argtypes = [ctypes.POINTER(OutPutImage), ctypes.c_int, ctypes.c_int, ctypes.c_int] output_image = OutPutImage(1, 2, 3) libc_adm.test_output_images(ctypes.byref(output_image), 4, 5, 6) print(np.array(output_image.output_img, dtype=np.float)) # error ocures here</pre><p> 當我使用以下 Makefile 制作並運行此代碼時</p><pre>by_ref: by_ref.so python by_ref.py by_ref.so: by_ref.o gcc -shared -o by_ref.so by_ref.o by_ref.o: by_ref.c gcc -c -Wall -fpic by_ref.c -o by_ref.o</pre><p> 我得到錯誤:</p><pre> Traceback (most recent call last): File "by_ref.py", line 46, in &lt;module&gt; print(np.array(output_image.output_img, dtype=np.float)) ValueError: '&lt;P' is not a valid PEP 3118 buffer format string make: *** [Makefile:2: by_ref] Error 1</pre><p> 我確信test_output_images正在做它應該做的事情。 但是我無法從結構中的數據構建 numpy 數組。 我該如何做到這一點? 另外,我什么時候釋放 memory? 謝謝。</p><p> <strong>編輯:</strong></p><p> 如果我使用np.ctypeslib.as_array(output_image.output_img)我得到同樣的錯誤:</p><pre> ValueError: '&lt;P' is not a valid PEP 3118 buffer format string</pre><p> <strong>更新:</strong></p><p> 如果我使用x = np.ctypeslib.as_array(( ctypes.c_double*array_length ).from_address( ctypes.addressof(output_image.output_img) )) ,其中array_length=nb_images*nb_cols*nb_rows ,那么我避免了上述錯誤,但是新數組 x 包含垃圾,無法重塑。</p></div></p'>

[英]Construct a numpy array from a C structure using ctypes. ValueError: '<P' is not a valid PEP 3118 buffer format string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 從文件構造結構化的numpy數組? 如何從 numpy 數組構造一個 ndarray? python 正確地從十六進制字符串轉換為字節數組 從不同大小的較小數組構造單個numpy數組 如何從一組現有數組構造一個新的numpy數組? 如何根據ID對齊的數據從多個向量構造一個numpy數組 如何從大量數據中有效構造一個numpy數組? 使用 ctypes 從 C 結構構造 numpy 數組。 值錯誤:' <p' is not a valid pep 3118 buffer format string< div><div id="text_translate"><p> 考慮以下代碼:</p><p> by_ref.h</p><pre> typedef struct OutPutImage{ double *** output_img; int nb_images; int nb_cols; int nb_rows; }opi_; void test_output_images(struct OutPutImage * out, int nb_images, int nb_cols, int nb_rows);</pre><p> by_ref.c</p><pre> #include &lt;stdlib.h&gt; #include "by_ref.h" void test_output_images(struct OutPutImage* out, int nb_images, int nb_cols, int nb_rows){ out-&gt;nb_images = nb_images; out-&gt;nb_cols = nb_cols; out-&gt;nb_rows = nb_rows; out-&gt;output_img = (double***)malloc((nb_images) * sizeof(double**)); for(int i = 0; i &lt; nb_images; i++){ out-&gt;output_img[i] = (double**)malloc((nb_cols) * sizeof(double*)); for(int j = 0; j &lt; nb_cols; j++){ out-&gt;output_img[i][j] = (double*)malloc((nb_rows) * sizeof(double)); for(int k = 0; k &lt; nb_rows; k++){ out-&gt;output_img[i][j][k] = 0; } } } }</pre><p> 和</p><p> by_ref.py</p><pre> import ctypes import numpy.ctypeslib as npct import numpy as np class OutPutImage(ctypes.Structure): _fields_ = [('output_img', npct.ndpointer(dtype=np.double, ndim=3)), ('nb_images', ctypes.c_int), ('nb_cols', ctypes.c_int), ('nb_rows', ctypes.c_int)] _libc = ctypes.CDLL("./by_ref.so") def __init__(self, nb_images=None, nb_cols=None, nb_rows=None): self.nb_images = nb_images self.nb_cols = nb_cols self.nb_rows = nb_rows if __name__ == '__main__': libc_adm = ctypes.CDLL("./by_ref.so") libc_adm.test_output_images.restype = ctypes.c_int libc_adm.test_output_images.argtypes = [ctypes.POINTER(OutPutImage), ctypes.c_int, ctypes.c_int, ctypes.c_int] output_image = OutPutImage(1, 2, 3) libc_adm.test_output_images(ctypes.byref(output_image), 4, 5, 6) print(np.array(output_image.output_img, dtype=np.float)) # error ocures here</pre><p> 當我使用以下 Makefile 制作並運行此代碼時</p><pre>by_ref: by_ref.so python by_ref.py by_ref.so: by_ref.o gcc -shared -o by_ref.so by_ref.o by_ref.o: by_ref.c gcc -c -Wall -fpic by_ref.c -o by_ref.o</pre><p> 我得到錯誤:</p><pre> Traceback (most recent call last): File "by_ref.py", line 46, in &lt;module&gt; print(np.array(output_image.output_img, dtype=np.float)) ValueError: '&lt;P' is not a valid PEP 3118 buffer format string make: *** [Makefile:2: by_ref] Error 1</pre><p> 我確信test_output_images正在做它應該做的事情。 但是我無法從結構中的數據構建 numpy 數組。 我該如何做到這一點? 另外,我什么時候釋放 memory? 謝謝。</p><p> <strong>編輯:</strong></p><p> 如果我使用np.ctypeslib.as_array(output_image.output_img)我得到同樣的錯誤:</p><pre> ValueError: '&lt;P' is not a valid PEP 3118 buffer format string</pre><p> <strong>更新:</strong></p><p> 如果我使用x = np.ctypeslib.as_array(( ctypes.c_double*array_length ).from_address( ctypes.addressof(output_image.output_img) )) ,其中array_length=nb_images*nb_cols*nb_rows ,那么我避免了上述錯誤,但是新數組 x 包含垃圾,無法重塑。</p></div></p'> 用pytables構造巨大的numpy數組 在numpy中構造這個數組的有效方法?
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM