簡體   English   中英

在python中將字符串轉換為numpy數組,反之亦然

[英]Converting string to numpy array and vice versa in python

我有一個numpy數組,這是打開cv讀取的圖像並將其保存為字符串。 所以我已經將np數組轉換為字符串並存儲相同的內容。 現在我想檢索值(這是一個字符串)並轉換為原始的numpy數組維度。 你能幫我解決一下這個問題嗎?

我的代碼如下:

img = cv2.imread('9d98.jpeg',0)
img.shape    # --> (149,115)
img_str=np.array2string(img,precision=2,separator=',') # to string length 197? which I dont know how
img_numpy=np.fromstring(img_str,dtype=np.uint8) # shape (197,) since this is returning only 1D array

請幫我解決一下

挑戰在於不僅要保存數據緩沖區,還要保存形狀和dtype。 np.fromstring讀取數據緩沖區,但作為1d數組; 你必須得到其他地方的dtype和形狀。

In [184]: a=np.arange(12).reshape(3,4)

In [185]: np.fromstring(a.tostring(),int)
Out[185]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [186]: np.fromstring(a.tostring(),a.dtype).reshape(a.shape)
Out[186]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

是json的選擇嗎?

這里答案:

import numpy as np
import json

img = np.ones((10, 20))
img_str = json.dumps(img.tolist())
img_numpy = numpy.array(json.loads(img_str))

暫無
暫無

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM