我有一个二维数组的图像(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()

original image

更新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

enter image description here enter image description here

推荐答案

Updated Answer

原来像素既是浮动的,也可能是负数,所以您可能需要一种可以存储此类内容的图像格式,即TIFF.

import numpy as np
from PIL import Image

# Make single channel 224x244 image of floats in range -2...+2    
slice = np.random.uniform(low=-2, high=2, size=(224,224))

# Convert to 224x224 to PIL 'F' Image
im = Image.fromarray(slice)
im.save('result.tiff')

只有几个注解:

  • TIFF文件可能会变得相当大,因为默认情况下它们是解压缩的,因此您可能希望try 不同的压缩options,以查看是否有适合您的数据的压缩

  • OpenCV也有FileStorage格式--但其他程序不能轻易查看

  • OpenCV也支持浮点数的OpenEXR格式,这很容易被其他软件查看

Original Answer

以下内容对您来说应该很好:

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>

enter image description here

Python相关问答推荐

如果索引不存在,pandas系列将通过索引获取值,并填充值

列表上值总和最多为K(以O(log n))的最大元素数

在Python中对分层父/子列表进行排序

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

Django管理面板显示字段最大长度而不是字段名称

连接两个具有不同标题的收件箱

通过pandas向每个非空单元格添加子字符串

如果条件不满足,我如何获得掩码的第一个索引并获得None?

根据列值添加时区

如何在图中标记平均点?

使用特定值作为引用替换数据框行上的值

在单次扫描中创建列表

寻找Regex模式返回与我当前函数类似的结果

合并与拼接并举

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

从嵌套极轴列的列表中删除元素

获取PANDA GROUP BY转换中的组的名称

如何在Python中解析特定的文本,这些文本包含了同一行中的所有内容,

如何将一个文件的多列导入到Python中的同一数组中?

对于数组中的所有元素,Pandas SELECT行都具有值