我有一个二维数组的图像(slice).数组的维度是(224,224),当我将其作为图像读取时,由于某种原因,我需要将其另存为"png"并显示它.我收到错误消息"ValueError:不支持从L到PNG的转换"
真实图像如下所示.请参见下面的代码.
from matplotlib import pyplot as plt
from PIL import Image
from matplotlib import cm
# reproducible data
slice = np.ones([224, 224], dtype = float)
print(slice.shape)
img_m3= Image.fromarray(slice)#.convert('RGB')#.convert('PNG')
print("img .mode",img_m3 .mode)
if img_m3 .mode != 'PNG':
img_m3 = img_m3.convert('PNG')
img_m3.save("/tmp/myimageb.png", "PNG")
im = Image.open("/tmp/myimageb.png")
plt.imshow(im )#, vmin=0, vmax=255)
plt.show()
最新情况:
我也try 将其另存为JPG,没有错误,但出现空白图像:
if img_m3 .mode != 'RGB':
img_m3 = img_m3.convert('RGB')
img_m3.save("/tmp/myimageb.jpg", 'JPEG')
#plt.imshow(img , cmap='gray', vmin=0, vmax=255)
im = Image.open("/tmp/myimageb.jpg")
plt.imshow(im )#, vmin=0, vmax=255)
plt.show()
更新2:
我try 了答案的解决方案,现在我可以看到图像了.但质量下降了.如下所示,上面是原始图像,下面是结果.
import cv2
from matplotlib import pyplot as plt
from PIL import Image
print(image[0].shape)
print("slice.max()",slice.max())
print("slice.min()",slice.min())
print("slice.mean()",slice.mean())
slice.min() and slice.mean()
#img = Image.fromarray((slice*255).astype(np.uint8)).convert('L')
img = Image.fromarray(slice.astype(np.uint8))
img.save("/tmp/myimageb.png", "PNG")
plt.imshow(img )#, cmap='gray', vmin=0, vmax=255)
plt.show()
(224, 224)
slice.max() 0.5193082
slice.min() -2.0836544
slice.mean() -0.37065452