我試圖在這段代碼中將 txt 檔案中的 jpeg 值轉換為 jpg 影像。捕獲影像的大小= 120 * 160,檔案中的值數= 2396(我不知道為什么總長度如此)。
我收到這個錯誤
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
ValueError: cannot reshape array of size 2396 into shape (120,160)
代碼:
# Open image file, slurp the lot
contents = Path('C://Users//hp//Desktop//file.txt').read_text()
# Make a list of anything that looks like numbers using a regex...
# ... taking first as height, second as width and remainder as pixels
h, w, *pixels = re.findall(r'[0-9] ', contents)
# Now make pixels into Numpy array of uint8 and reshape to correct height, width and depth
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
# Now make the Numpy array into a PIL Image and save
Image.fromarray(na).save('C://Users//hp//Desktop//jp.jpg')
uj5u.com熱心網友回復:
不需要 PIL 庫。您已經有一個 JPEG 檔案。
只需將這些數字轉換為位元組并保存即可。
with open("C://Users//hp//Desktop//file.txt", "r") as f:
data = f.read()
data = data.split(",") # split the numbers
data = [int(b) for b in data] # convert them to integers
data = data[2:] # remove width and height
data = bytes(data) # convert the array of numbers to bytes
with open("C://Users//hp//Desktop//jp.jpg", "wb") as f:
f.write(data)
結果:

注意:最后似乎缺少資料。您可能沒有捕獲所有資料。
您聲稱有 2396 個值,但您的示例有 3842 個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334212.html
上一篇:沿自己的路徑移動點
下一篇:如何調整次要刻度數
