python 从numpy读取图像并显示它:ValueError:不支持从L转换为PNG

cuxqih21  于 8个月前  发布在  Python
关注(0)|答案(1)|浏览(128)

我有一个图像的2D数组(slice)。数组维度为(224,224),当我将其作为图像读取时,如下所示,* 图像模式显示为“F”*,由于某种原因,我需要保存为“PNG”并显示它。我得到错误消息“ValueError:conversion from L to PNG not supported”
真实的图像如下所示。请参阅下面的代码。

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()

字符串
更新:
我也试过将其保存为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()


的数据

iq3niunx

iq3niunx1#

以下几点对你来说应该很好:

import numpy as np
from PIL import Image

# Make single channel 224x244 image of floats in range 0..255    
slice = np.random.rand(224,224) * 255

# Convert to 224x224 array of uint8 and then to PIL 'L' Image
im = Image.fromarray(slice.astype(np.uint8))
im.save('result.png')

print(im)        # prints <PIL.Image.Image image mode=L size=224x224>

字符串


的数据

相关问题