【发布时间】:2019-09-03 20:17:32
【问题描述】:
我有一张黑色背景的图像,其中包含不同颜色的不同形状。我想为每个形状生成一个图像,其中形状为白色,背景为黑色。我已经能够用 numpy 做到这一点,但我想使用矢量化来优化我的代码。这是我目前所拥有的:
import numpy as np
import cv2
image = cv2.imread('mask.png')
image.shape
# (720, 1280, 3)
# Get all colors that are not black
colors = np.unique(image.reshape(-1,3), axis=0)
colors = np.delete(colors, [0,0,0], axis=0)
colors.shape
# (5, 3)
# Example for one color. I could do a for-loop, but I want to vectorize instead
c = colors[0]
query = (image == c).all(axis=2)
# Make the image all black, except for the pixels that match the shape
image[query] = [255,255,255]
image[np.logical_not(query)] = [0,0,0]
【问题讨论】:
标签: python numpy opencv numpy-ndarray array-broadcasting