首页 > 解决方案 > 获取图像的 RGB 通道

问题描述

我正在尝试将一个三维 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

有任何想法吗?

标签: pythonnumpyopencvcv2

解决方案


如果您想要由 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)

推荐阅读