簡體   English   中英

如何將由 0 和 1 組成的數組轉換為二進制圖像?

[英]How do I convert an array of arrays consisting of 0s and 1s into a binary image?

我正在做一個項目,我必須生成一個隨機的二進制圖像(即由黑白像素組成的圖像 - 1 代表黑色,0 代表白色)。 像這樣:

在此處輸入圖像描述

然后將其轉換為 numpy 數組並保存到 txt 文件中,如下所示(截斷結果):

[[0 1 0 ... 0 0 1] [1 1 1 ... 0 0 0] [1 0 0 ... 0 1 0] ... [0 1 1 ... 1 0 1] [1 1 0 ... 0 1 1] [0 1 1 ... 0 1 0]]

現在我需要獲取該二進制數組並將其轉換回上面示例中的圖像。 這是我到目前為止用於此操作的代碼:

import numpy as np
from PIL import Image as im

array = np.genfromtxt('binary_array.txt', dtype=int)
print(array)
print(array.shape)
data = im.fromarray(array)
data.save('new_img.png')

(我使用打印語句只是為了更好地了解正在發生的事情以及可能缺少的內容)。 不幸的是,我所得到的,是一個黑色的圖像。 我確定我在這里遺漏了一些重要的東西,但我似乎什么都想不起來。 謝謝

您還可以將 matplotlib 與裸數組一起使用,而不是 PIL

from matplotlib import pyplot as plt
arr = np.array([[0,0,1,0], [1,0,0,0], [1,0,0,0], 
[0,0,0,0]])
plt.imshow(arr, cmap='gray')
plt.savefig('img.png', cmap='gray')

您可以將此數組計時 255,然后使用Image.fromarray方法將其轉換為PIL.Image對象。

from PIL import Image
import numpy as np

rand_array = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8)
im = Image.fromarray(rand_array * 255)
im.show()

在此處輸入圖像描述

暫無
暫無

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

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