首页 > 解决方案 > 如何在使用不同 np 形状的地方使用 np

问题描述

我想更有效地使用代码。

我现在通过参考图像形式的值来转换图像的颜色

很多人都知道,它与图像分割有关。

我通过深度学习模型得到了 Image [Width]*[Height] 的类值。

我想以原始颜色绘制分段区域,另一个以灰色绘制

下面是我的结果。人的部分是分割的区域

在此处输入图像描述

def read_video_frame(video_path):

    cap = cv2.VideoCapture(video_path)

    while(cap.isOpened()):
        ret, frame = cap.read()

        frame = cv2.resize(frame, dsize=(448, 448), interpolation=cv2.INTER_AREA)

        image = np.array(frame)

        mask = model_run(image)  # Deep learning model 

        gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255

        if mask is None:
            segmented_image = gray.astype(np.uint8)
        else:
            segmented_image[:, :, 0] = np.where(mask >= 1, image[:, :, 0], gray[:, :, 0])
            segmented_image[:, :, 1] = np.where(mask >= 1, image[:, :, 1], gray[:, :, 1])
            segmented_image[:, :, 2] = np.where(mask >= 1, image[:, :, 2], gray[:, :, 2])

        cv2.imshow('video', segmented_image)

        if cv2.waitKey(1) & 0xff == ord('q'):
            break

    cap.release()

您会在图像中发现代码中令人不舒服的部分。

比如我通过一个深度学习模型得到(5*5)的类值

NumPy 数组的形式如下。

ex = np.array([[0,0,1,0,0],
               [0,1,1,1,1],
               [0,0,1,1,1],
               [0,0,0,2,2],
               [0,0,1,2,2]
                          ])

如果数组的值大于1,则使用原始图像值,如果为0,则使用灰度图像值。

所以,我想用 np.where() 来一次处理它。

segmented_image[:, :] = np.where(mask >= 1, image[:, :], gray[:, :])

但我得到了这个错误

ValueError:操作数无法与形状一起广播 (448,448) (448,448,3) (448,448,3)

(我的目标图像尺寸是 448x448)

因为如您所知,图像像素的 NumPy 形状是 (width, height, 3)。

于是我被迫将r,g,b分成三个部分,形成一个图像。

segmented_image[:, :, 0] = np.where(mask >= 1, image[:, :, 0], gray[:, :, 0])
segmented_image[:, :, 1] = np.where(mask >= 1, image[:, :, 1], gray[:, :, 1])
segmented_image[:, :, 2] = np.where(mask >= 1, image[:, :, 2], gray[:, :, 2])

我怎样才能更清楚地编写代码?

标签: pythonnumpyimage-segmentation

解决方案


推荐阅读