python - 如何加快查找哪个图像像素颜色不在给定颜色列表中

标签 python image opencv

目的:我想加快查找哪个图像像素值不包含给定 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)

最佳答案

可能有比这更快的方法,但这只是一个开始!我的钱在@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) 

开始.png

enter image description here

结果:

enter image description here

关于python - 如何加快查找哪个图像像素颜色不在给定颜色列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53999778/

相关文章:

c++ - OpenCV 中 Mat 等结构的内存分配

opencv - 对象识别使用筛选描述符

python - 在 flask 中,我应该手动捕获 View 中所有可能的错误吗?

python - 带 Eclipse 的 Google App Engine?

PHP水印

php - imagecolortransparent() 在 PHP 中将所有黑色像素变为透明

python - 如何确定是否在命令行上实际指定了 argparse 参数?

Python:如何使用日志记录模块每天创建日志文件?

ios - 图像不会动画

c++ - 使用 OpenCV 移动 cv::Mat 的高效 C++ 方法