Python:在opencv中手动合并通道

时间:2018-09-23 11:55:54

标签: python numpy opencv numpy-broadcasting numpy-ndarray

def frame_processing(frame):
out_frame = np.zeros((frame.shape[0],frame.shape[1],4),dtype = np.uint8)
b,g,r = cv2.split(frame)
alpha = np.zeros_like(b , dtype=np.uint8)
print(out_frame.shape)
print(b.shape);print(g.shape);print(r.shape);print(alpha.shape)
for i in range(frame.shape[0]):
    for j in range(frame.shape[1]):
        a = (frame[i,j,0],frame[i,j,1],frame[i,j,2])
        b = (225,225,225)
        if all(i > j for i, j in zip(a,b)):  #all(a>b) :
            alpha[i,j] = 0
        else:
            alpha[i,j] = 255
out_frame[:,:,0] = b
out_frame[:,:,1] = g
out_frame[:,:,2] = r
out_frame[:,:,3] = alpha
#out_frame = cv2.merge((b,g,r,alpha))
return out_frame

想添加一个Alpha通道;尝试cv2.Merge()和手动堆叠渠道,但失败了。

使用cv2.merge()时:

error: OpenCV(3.4.2) C:\projects\opencv- 
python\opencv\modules\core\src\merge.cpp:458: error: (-215:Assertion failed) 
mv[i].size == mv[0].size && mv[i].depth() == depth in function 'cv::merge'

手动添加频道时:

ValueError: could not broadcast input array from shape (3) into shape 
(225,225)

2 个答案:

答案 0 :(得分:3)

使用isVideoMirrored查找遮罩,然后将其与cv2.inRange合并:

np.dstack

要找到特定的颜色,也许您会对以下问题感兴趣:

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

答案 1 :(得分:0)

它是一个简单的错字。您正在for循环中更改变量“ b”,它与蓝色通道的变量冲突。将b = (225,225,225)更改为threshold = (225, 255, 255),将zip(a,b)更改为zip(a, threshold)应该可以解决此问题。
顺便说一下,您可以使用它来创建您的Alpha通道:

alpha = np.zeros(b.shape, dtype=b.dtype)

如果您需要更高的速度(可以测量时差),也可以像这样填充Alpha通道:

alpha[~((b[:,:]>threshold[0]) & (g[:,:]>threshold[1]) & (r[:,:]>threshold[2]))] = 255

因此您的功能变为:

def frame_processing(frame):
    #  split channels
    b,g,r = cv2.split(frame)

    #  initialize alpha to zeros
    alpha = np.zeros(b.shape, dtype=b.dtype)

    #  fill alpha values
    threshold = (225, 225, 225)
    alpha[~((b[:,:]>threshold[0]) & (g[:,:]>threshold[1]) & (r[:,:]>threshold[2]))] = 255

    #  merge all channels back
    out_frame = cv2.merge((b, g, r, alpha))

    return out_frame