【问题标题】:Python OpenCV - How to save a 5 channel imagePython OpenCV - 如何保存 5 通道图像
【发布时间】:2020-04-05 23:54:23
【问题描述】:

我将 Google Colab 与 Python 3 结合使用,我需要合并 3 张图像以创建一个具有 5 个通道的新图像,但出现此错误:

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_'

我知道cv2.imwrite 不保存 5 通道图像,但我该怎么做呢?

这是我的代码:

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)

【问题讨论】:

标签: python-3.x numpy opencv image-processing google-colaboratory


【解决方案1】:

由于 opencv 使用 numpy 数组,您可以使用 numpy.save(二进制)或 numpy.savez_compressed(压缩 zip)保存图像。

例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多