Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force python to write 3 channel png image

I am writing some scripts to do image processing (preparing large batches of image data for use in a convolutional neural network). As a part of that process, I am tiling a single large image into many smaller images. The single large image is a 3-channel (RGB) .png image. However, when I use matplotlib.image.imsave to save the image, it becomes 4-channel. A minimal working example of code is below (note python 2.7).

#!/usr/bin/env python
import matplotlib.image as mpimg

original_image = mpimg.imread('3-channel.png')
print original_image.shape

mpimg.imsave('new.png', original_image)

unchanged_original_image = mpimg.imread('new.png')
print unchanged_original_image.shape

The output of which is:

(300, 200, 3)

(300, 200, 4)

My question is: Why does matplotlib.image.imsave force the 4th channel to be there? and (most importantly) what can I do to make sure only the 3 color channels (RGB) are saved?

The example image I created is below:

enter image description here

like image 410
TravisJ Avatar asked Nov 15 '16 15:11

TravisJ


1 Answers

If it doesn't need to be matplotlib you could use scipy.misc.toimage()

import matplotlib.image as mpimg
import scipy.misc

original_image = mpimg.imread("Bc11g.png")
print original_image.shape
# prints (200L, 300L, 3L)

mpimg.imsave('Bc11g_new.png', original_image)
unchanged_original_image = mpimg.imread('Bc11g_new.png')
print unchanged_original_image.shape
# prints (200L, 300L, 4L)

#now use scipy.misc
scipy.misc.toimage(original_image).save('Bc11g_new2.png')
unchanged_original_image2 = mpimg.imread('Bc11g_new2.png')
print unchanged_original_image2.shape
# prints (200L, 300L, 3L)

Note that scipy.misc.toimage is deprecated as of v1.0.0, and will be removed in 1.2.0 https://docs.scipy.org/doc/scipy-1.2.1/reference/generated/scipy.misc.toimage.html

like image 176
ImportanceOfBeingErnest Avatar answered Sep 20 '22 07:09

ImportanceOfBeingErnest