所以我有这个代码使用高重要性的第四位将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")
答案 0 :(得分:0)
y
是一个布尔数组。因此,当您将其转换为uint8
时,您的值都是0或1。
但是当您从Image
创建y
时,指定模式'L'
,即8 bits per pixel。
因此您可以简单地将像素缩放到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")
输出:
答案 1 :(得分:0)
最终图像并非全黑。它非常暗,因为所有像素都是0(黑色)或1(几乎是黑色)。毕竟,y
是0或1(假或真)。 imshow
缩放范围,以便您看到的东西不像实际上那样黑。您确定需要将y
转换为图像吗?
顺便说一下,z
是不必要的。将循环中的行写为x = x - y * (2**(7-i))