How to save a 2-channel image to a folder?

Viewed 178

I am concatenating two 1-channel grayscale images into one 2-channel image and writing it to a folder.

import struct
import zlib     
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
import pandas as pd
import cv2
import numpy as np
import glob
import os
from keras.preprocessing import image
import imageio

filenames1 = glob.glob("folder1/*.png")
filenames1.sort()
filenames2 = glob.glob("folder2/*.png")
filenames2.sort()

for f1,f2 in zip(filenames1,filenames2):
    img_name = os.path.basename(f1)
    img_name = img_name[:-4] + ".png"
    img1 = Image.open(f1)
    img2 = Image.open(f2)
    
    img1a = image.img_to_array(img1)
    img2a = image.img_to_array(img2)
    
    # Merged image
    merge_image = np.concatenate((img1a, img2a), axis=2)
    # plt.imsave('folder3/{}.png'.format(img_name[:-4]),merge_image)
    imageio.imwrite('folder4/{}.png'.format(img_name[:-4]),merge_image)

When I used matplotlib's 'imsave' function, I got the following error:

ValueError: Third dimension must be 3 or 4

When I used Imageio 'imwrite' function, I got the following error:

ValueError: Image must be 2D (grayscale, RGB, or RGBA)

How can I write the 2-channel image to a folder in this case?

1 Answers

As your error stack says, you cannot use matplotlib.imsave or imageio.imwrite as they support only 1 (grayscale), 3 (rgb, bgr, hsv etc...) or 4 (same as 3 + alpha channel). I don't know if png format does support 2 channels at all, but if it does the result would be a single channel image (grayscale) + alpha channel.

The solution depends on what these images do represent and what you're actually trying to achieve:

  • if you want to save single channel image + alpha channel, you'd better to replicate the first channel 3 times, so that your channels are (BW, BW, BW, alpha)
  • if you're fusing two spatial informations, for example angle and magnitude of an optical flow, you have to do the conversion manually (OpenCV displaying a 2-channel image (optical flow)) and fill the remaining channel with something else.
  • if you're only trying to stack two images and save them, png is not the correct solution. You could stack them using numpy and save/store them as .npy objects.
Related