目的:我想加快查找在给定RGB颜色表中哪个图像像素值不包含颜色之一的过程,并将它们映射到后缀为_mistakes.png
的另一张图像。
考虑到图像的大尺寸,使用两个for循环分别处理每个像素会花费很长时间。
import glob
import numpy as np
import os
import cv2
import os.path
# the given list of defined RGB colors.
CLASSES = {
0: [0, 0, 0],
1:[255, 0, 0],
2:[0, 0, 255],
3:[0, 255, 0],
4:[50, 255, 50],
5:[100, 255, 100]
}
for image_path in glob.glob("*.png"):
name = os.path.split(image_path)[-1]
_name = os.path.splitext(name)[0]
img = cv2.imread(image_path)
img_height, img_width, _ = img.shape
img_mistakes = np.zeros((img.shape))
color_codes = np.array(list(CLASSES.values()))
# the following two for loops take so long.
for row in range(img_height):
for col in range(img_width):
if not (img[row,col] == color_codes).all(1).any():
img_mistakes[row, col] = [200, 200, 200] # a chosen color
cv2.imwrite(_name + '_mistakes' + '.png', img_mistakes)
答案 0 :(得分:1)
可能有比这更快的方法,但这是一个开始!我的钱在@divakar上知道-提示,提示;-)
#!/usr/local/bin/python3
import numpy as np
import cv2
# Open image into numpy array
im=cv2.imread('start.png')
# Work out how one pixel of each colour we are looking for looks
black = [0,0,0]
blue = [255,0,0]
red = [0,0,255]
green = [0,255,0]
# Find all pixels where the 3 RGB values match the sought colour
blacks = np.all(im==black, axis=2)
blues = np.all(im==blue , axis=2)
reds = np.all(im==red , axis=2)
greens = np.all(im==green, axis=2)
# Make empty (black) output array same size as input image
mistakes = np.zeros_like(im)
# Make anything not matching any of our colours into [200,200,200]
mistakes[~(blacks | blues | reds | greens)] = [200,200,200]
# Save result
cv2.imwrite("result.png",mistakes)
start.png
结果: