python-3.x - Python OpenCV - 如何保存 5 channel 图像

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

我将 Google Colab 与 Python 3 一起使用,我需要合并 3 个图像以制作一个具有 5 个 channel 的新图像,但出现此错误:
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 channel 图像,但我该怎么做?

这是我的代码:

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)

最佳答案

由于 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)

关于python-3.x - Python OpenCV - 如何保存 5 channel 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59307148/

相关文章:

python - 使用python将 'repetitive' 2D数组转换为矩阵

python - 在python中矢量化特征散列

python - 如果子列表的第一个元素在 Python 中是唯一的,则从第一个子列表中获取前两项

python - pymysql 错误 : 'str' object has no attribute 'nextset'

python-3.x - 无法从 Tornado Client 连接到基于 Tornado SSL 的服务器

python - 如何使__slots__更好地使用数据类?

python - 在Python中选择和迭代多维数组中的特定子数组

c++ - cv::split 或 Eigen::Stride:哪个更有效地将多 channel 矩阵从 OpenCV 映射到 Eigen 结构

opencv - 使用OpenCV在Calibr3d_StereoCalibrate在ARM64bit上失败

python - 对象提取与构建