获取图像的RGB通道

时间:2019-03-14 11:06:04

标签: python numpy opencv cv2

我试图将三维numpy数组拆分为红色,绿色和蓝色层。

到目前为止,我具有以下功能:     s_W是屏幕宽度,s_H是屏幕高度

def webcam_func(cap, s_W, s_H):
    # Capture frame by frame
    ret, frame = cap.read()

    if ret:
        # make a np array from the frame
        frame_one = np.array(frame)

        # seperate the height, width and depth of the array
        arr_height = (frame_one.shape[0])
        arr_width = (frame_one.shape[1])
        arr_rgb = (frame_one.shape[2])

        # This is what I tried to get a copy of the whole 
        # array except for the first depth slice, 
        # which I believe is RED channel
        green_frame = frame_one[0:arr_height, 0:arr_width, 0:1]

        # flip the frame
        frame_flip = np.rot90(green_frame)

        # create a pygame surface and then scale the surface
        webcam_frame = pyg.surfarray.make_surface(frame_flip)
        webcam_frame = pyg.transform.scale(webcam_frame, (s_W, s_H))

        return(webcam_frame)

但是,尝试从切片框架创建曲面时出现此错误。

ValueError: must be a valid 2d or 3d array

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

如果您想要由numpy数组表示的图像的rgb通道,则可以使用:

b,g,r = cv2.split(frame)

或:

b = frame[:,:,0]
g = frame[:,:,1]
r = frame[:,:,2]

因此您可以更改功能:

def webcam_func(cap, s_W, s_H):
    # Capture frame by frame
    ret, frame_one = cap.read()

    if ret:


    # seperate the height, width and depth of the array
        arr_height = (frame_one.shape[0])
        arr_width = (frame_one.shape[1])
        arr_rgb = (frame_one.shape[2])

        green_frame = frame_one[:,:, 1] #This will return the green channel

    # flip the frame
        frame_flip = np.rot90(green_frame)

    # create a pygame surface and then scale the surface
        webcam_frame = pyg.surfarray.make_surface(frame_flip)
        webcam_frame = pyg.transform.scale(webcam_frame, (s_W, s_H))

        return(webcam_frame)