'Python OpenCV - How to save a 5 channel image

I'm using Google Colab with Python 3 and I need to merge 3 images to make a new one with 5 channels, but i get this error:

error: OpenCV(4.1.2) /io/opencv/modules/imgcodecs/src/loadsave.cpp:668: error: (-215:Assertion failed) image.channels() == 1 || image.channels() == 3 || image.channels() == 4 in function 'imwrite_'

I understand that cv2.imwrite doesn't save a 5 channel image, but how can I do it?

Here is my code:

import numpy as np
import matplotlib.pyplot as plt
import cv2

"""Read each channel into a numpy array. 
Of course your data set may not be images yet.
So just load them into 5 different numpy arrays as neccessary"""
imgRGB = cv2.imread("/content/drive/My Drive/teste/LC08_L1TP_222063_20180702_20180716_01_T1_1_3.tif")
b,g,r = cv2.split(imgRGB)
tir = cv2.imread("/content/drive/My Drive/teste/LC08_L1TP_222063_20180702_20180716_01_T1_TIR_1_3.tif", 0)
qb = cv2.imread("/content/drive/My Drive/teste/LC08_L1TP_222063_20180702_20180716_01_T1_QB_1_3.tif", 0)

"""Create a blank image that has 5 channels 
and the same number of pixels as your original input"""
needed_multi_channel_img = np.zeros((b.shape[0], b.shape[1], 5))

"""Add the channels to the needed image one by one"""
needed_multi_channel_img [:,:,0] = b
needed_multi_channel_img [:,:,1] = g
needed_multi_channel_img [:,:,2] = r
needed_multi_channel_img [:,:,3] = tir
needed_multi_channel_img [:,:,4] = qb

"""Save the needed multi channel image"""
cv2.imwrite("/content/drive/My Drive/teste/Merged_5C.tif",needed_multi_channel_img)


Solution 1:[1]

Since opencv uses numpy arrays, you can save your image using numpy.save (binary) or numpy.savez_compressed (compressed zip).

For example:

import numpy as np
filepath = "/content/drive/My Drive/teste/Merged_5C.npy"
with open(filepath, 'w') as f:
    np.save(f, needed_multi_channel_img, allow_pickle=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1