簡體   English   中英

Lenna壓縮保存所有黑色python

[英]Lenna compression save all black python

因此,我有這段代碼使用高位有效的第四位將lena.tif圖像壓縮為黑白。 當我保存圖像時,最終的結果是全黑,而我不知道為什么,這是我的問題。

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

x_img = Image.open("lenac.tif")
x_gray = x_img.convert("L")
x = np.array(x_gray)
for i in range(0,4):
    y = x > (2**(7-i))-1
    z = x - y * (2**(7-i))
    x = z    

new_img = Image.fromarray(y.astype('uint8'),'L')
plt.imshow(new_img, cmap='gray')
new_img.save("lena_4 .bmp")

y是一個布爾數組。 因此,當您將其轉換為uint8您的值全為0或1。

但是,當您從y創建Image時,需要指定模式'L' ,即每像素8位

因此,您可以簡單地將像素縮放到8位范圍:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

x_img = Image.open("lenac.tif")
x_gray = x_img.convert("L")
x = np.array(x_gray)
for i in range(0,4):
    y = x > (2**(7-i))-1
    z = x - y * (2**(7-i))
    x = z

y = y.astype('uint8') * 255        # This scales the pixel values

new_img = Image.fromarray(y ,'L')  # Use y here instead of y.astype(...)
plt.imshow(new_img, cmap='gray')
#plt.show()
new_img.save("lena_4.bmp")

輸出:

在此處輸入圖片說明

最終圖像並非全黑。 因為所有像素均為0(黑色)或1(幾乎黑色),所以它非常暗。 畢竟, y是0或1(False或True)。 imshow縮放范圍,以使您看到的東西並非真正的黑色。 您確定需要將y轉換為圖像嗎?

順便說一下, z是不必要的。 將循環中的行寫為x = x - y * (2**(7-i))

暫無
暫無

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

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