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

时间:2017-08-09 14:41:22

标签: python matplotlib rgb rgba scikit-image

我需要将形状为H*W*4的PNG 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我有什么想法吗?

参考图片:

enter image description here

修改 像这样更新的代码:

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

1 个答案:

答案 0 :(得分:2)

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图像,则需要使用其他方法来保存图像。

E.g。使用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)