簡體   English   中英

如何將黑白像素圖像轉換為文本?

[英]How do I convert a black and white pixel image to text?

我有一個白色背景上帶有黑色像素的 png 文件。 我試圖找到一種方法將其轉換為二進制值文本文件。

也就是說,我想要一種方法,將一個 4 像素的黑白 png 變成看起來像

XX

變成讀起來像的文本

11
01

我最好的引導是安裝 PIL,但要么我沒有安裝正確的東西,要么這不符合我的想法,因為我收到了“名稱 'pix' 未定義”錯誤。

from PIL import Image

im = Image.open("image.jpg")
fil = open('file', 'w')
pixel = im.load()
row, column = im.size
for y in range(column):
    for x in range(row):
        pixel = pix[x,y]
        fil.write(str(pixel) + '\n')
fil.close()

任何幫助或線索將不勝感激

pix 確實沒有定義。 您將 PixelData 保存到“像素”變量中,即存儲像素的位置。

您可以通過以下方式獲取每個像素:pixel[x,y] 而不是 pix[x,y]。 嘗試更換

fil.write(str(pixel) + '\n')

和:

fil.write(str(pixel[x,y]) + '\n')

您可以將像素存儲在變量中,就像您在

pixel = pix[x,y]

但是為此,您必須將變量命名為其他名稱,因為像素是您的 PixelData 變量的名稱。 你可以這樣做:

pix = pixel[x,y]
fil.write(str(pix) + '\n')

您可以嘗試以下將黑白圖像轉換為二進制文本的代碼:

from PIL import Image
import numpy as np

img = Image.open('<path-to-image>/bw.png').convert('L') #this is needed to convert the image to grayscale. PIL by default opens it as RGB.

np_img = np.array(img)
np_img[np_img > 0] = 1
print(np_img) # prints the binary text in matrix

更多參考: https : //pillow.readthedocs.io/en/stable/reference/Image.html

暫無
暫無

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

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