【问题标题】:Python: merging channels in opencv and manuallyPython:在opencv中合并通道并手动
【发布时间】:2019-02-27 04:04:33
【问题描述】:
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)

【问题讨论】:

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


    【解决方案1】:

    这是一个简单的错字。您正在更改 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
    

    【讨论】:

    • 非常感谢兄弟。我一遍又一遍地检查它,但找不到这个非常愚蠢的东西,也感谢你提供的多余信息
    【解决方案2】:

    使用cv2.inRange 找到掩码,然后将它们与np.dstack 合并:

    #!/use/bin/python3
    # 2018/09/24 11:51:31 (CST)
    import cv2
    import numpy as np
    
    #frame = ...
    mask = cv2.inRange(frame, (225,225,225), (255,255,255))
    
    #dst = np.dstack((frame, 255-mask))
    dst = np.dstack((frame, mask))
    
    cv2.imwrite("dst.png", dst)
    

    要找到具体的颜色,也许你会对这个问题感兴趣:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2017-07-07
      • 2011-03-03
      相关资源
      最近更新 更多