使用numpy将图像分成通道

时间:2019-03-02 14:37:48

标签: python numpy opencv opencv3.0

我想分离图像的通道。然后,我想将Otsu阈值应用于每个阈值,最后将它们合并在一起。但是,在我的代码的第4行中,它给了我以下错误:

test's

这是我的代码:

File "C:/Users/Berke/PycharmProjects/goruntu/main.py", line 28, in <module>
    image_channels = np.split(np.asarray(gradient_image), 3, axis=2)
File "C:\Users\Berke\PycharmProjects\goruntu\venv\lib\site-packages\numpy\lib\shape_base.py", line 846, in split
    N = ary.shape[axis]
IndexError: tuple index out of range

1 个答案:

答案 0 :(得分:2)

为什么没有更简单的方法?

import numpy as np
import cv2

original_image = cv2.imread(path) #expect [X,Y,3] shape
#or
original_image = np.asarray(gradient_image)

otsu_image = np.zeros(shape=original_image.shape)
for channel in range(3):
    _,otsu_image[:,:,channel]= cv2.threshold(original_image[:,:channel],0,255,cv2.THRESH_OTSU | cv2.THRESH_BINARY)

通过此[:,:,channel]索引选择,您基本上可以访问特定通道的图像层,而无需对图像进行任何特殊处理。当然,您可以将阈值图像分配给该层,因为1通道层的尺寸与灰度图像的尺寸相同