欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Color Detection 颜色定位

程序员文章站 2022-06-01 10:46:40
...

简介

使用Python、cv2的颜色定位,mask图像,需要取定颜色取值范围。

代码

'''
Created on 2017年8月20日

@author: XT
'''
# import the necessary packages
import numpy as np
import argparse
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image")
args = vars(ap.parse_args())

# load the image
image = cv2.imread(args["image"])
# define the list of boundaries
#We are performing color detection in the RGB color space. 
#R >= 100, B >= 15, and G >= 17 along with R <= 200, B <= 56, and G <= 50 will be considered red.
boundaries = [
    ([17, 15, 100], [50, 56, 200]),#Red
    ([86, 31, 4], [220, 88, 50]),#Gree
    ([25, 146, 190], [62, 174, 250]),#
    ([103, 86, 65], [145, 133, 128])#Gray
]

# loop over the boundaries
for (lower, upper) in boundaries:
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype = "uint8")
    upper = np.array(upper, dtype = "uint8")

    # find the colors within the specified boundaries and apply
    # the mask
    mask = cv2.inRange(image, lower, upper)
    output = cv2.bitwise_and(image, image, mask = mask)

    # show the images
    cv2.imshow("images", np.hstack([image, output]))
    cv2.waitKey(0)
    #python detect_color.py --image pokemon_games.png

效果

Color Detection 颜色定位
Color Detection 颜色定位
Color Detection 颜色定位
Color Detection 颜色定位