skimage.color rgba 转 rgb 的图像被 matplotlib imsave 保存为 rgba

Image converted by skimage.color rgba to rgb is saved as rgba by matplotlib imsave

我需要将 PNG H*W*4 rgba 图像转换为 rgb 形状为 H*W*3 的图像。

我可以做到,但是当我保存它时,图像又被保存为 H*W*4 这是代码片段:

for idx, image in enumerate(image_names):
    #matplotlib as mpi here I use plt for plotting and mpi for read
    rgba = mpi.imread(os.path.join(read_path,image))
    #convert to rgb using skimage.color as rtl,
    rgb = rtl.rgba2rgb(rgba)
    #change path of the image to be saved
    resized_path = os.path.join(os.path.sep,Ims,p[0],image)
    print(np.shape(rgb))#shape is printed (136,136,3)
    mpi.imsave(resized_path,rgb)

在此之后,当我再次阅读它时,它的形状又是 H*W*4 知道为什么吗?我猜 matplotlib imsave 有什么用吗?

参考图片:

编辑 更新代码如下:

for idx, image in enumerate(image_names):
    rgba = plt.imread(os.path.join(read_path,image))
    rgb = skimage.color.rgba2rgb(rgba)
    #original image name do not have ext and adding or removing 
    # does not effect
    resized_path = os.path.join(os.path.sep,basepath,image,".png")
    rgb = Image.fromarray((rgb*255).astype(np.uint8))
    rgb.save(resized_path)

出现以下错误:

    ValueError                                Traceback (most recent call last)
<ipython-input-12-648b9979b4e9> in <module>()
      6         print(np.shape(rgb))
      7         rgb = Image.fromarray((rgb*255).astype(np.uint8))
----> 8         rgb.save(resized_path)
      9     #mpi.imsave(resized_path,rgb)

/usr/local/lib/python2.7/dist-packages/PIL/Image.pyc in save(self, fp, format, **params)
   1809                 format = EXTENSION[ext]
   1810             except KeyError:
-> 1811                 raise ValueError('unknown file extension: {}'.format(ext))
   1812 
   1813         if format.upper() not in SAVE:

ValueError: unknown file extension:

解决方案 下面解决的答案是正确的,上面唯一的问题是调整了路径大小,这里进行了更改:

resized_path = os.path.join(os.path.sep,Ims,p[0],image)
resized_path = (resized_path+".png")

Matplotlib pyplot.imsave 使用 alpha 通道(即作为 RGBA)保存图像,这与输入数组是否存在这样的通道无关。

但是,没有信息丢失,因为所有 alpha 值都是 1。因此,您可以获得 RGB 图像

new_im = plt.imread("image.png")[:,:,:3]
# new_im.shape will be (<y>, <x>, 3)

如果您特别需要 RGB png 图像,则需要使用不同的方式来保存图像。

例如使用 PIL

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

im = np.random.rand(120,120,3)

im2 = Image.fromarray((im*255).astype(np.uint8))
im2.save("image2.png")

new_im = plt.imread("image2.png")  
print (new_im.shape)
# prints  (120L, 120L, 3L)