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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With