python opencv选取特定颜色区域

import cv2
import numpy as np
# 回调函数,x表示滑块的位置,本例暂不使用
def nothing(x):
    pass
def ColorDetector(img, lower=np.array([20, 50, 46]), upper=np.array([60, 255, 255])):
    """
     提取颜色图像
    :param img:
    :param lower:
    :param upper:
    :return:
    """
    Hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # mask -> 1 channel
    mask_green = cv2.inRange(Hsv, lower, upper)
    res = cv2.bitwise_and(img, img, mask = mask_green)
    return res

img = cv2.imread(r"D:\cycFeng\Data\tree1.jpg")
img = cv2.resize(img,None,None,0.6,0.6)
img_copy = img.copy()
# img = np.zeros((300, 512, 3), np.uint8)
cv2.namedWindow('image')
cv2.moveWindow('image',100,100)
# 创建RGB三个滑动条
cv2.createTrackbar('H_Low', 'image', 0, 255, nothing)
cv2.createTrackbar('H_High', 'image', 0, 255, nothing)

cv2.createTrackbar('S_Low', 'image', 0, 255, nothing)
cv2.createTrackbar('S_High', 'image', 0, 255, nothing)

cv2.createTrackbar('V_Low', 'image', 0, 255, nothing)
cv2.createTrackbar('V_High', 'image', 0, 255, nothing)


while(True):
    cv2.imshow('im', img)
    if cv2.waitKey(1) == 27:
        break

    # 获取滑块的值
    H_Low = cv2.getTrackbarPos('H_Low', 'image')
    H_High = cv2.getTrackbarPos('H_High', 'image')

    S_Low = cv2.getTrackbarPos('S_Low', 'image')
    S_High = cv2.getTrackbarPos('S_High', 'image')

    V_Low = cv2.getTrackbarPos('V_Low', 'image')
    V_High = cv2.getTrackbarPos('V_High', 'image')
    # 设定img的颜色
    lower_green = np.array([H_Low, S_Low, V_Low])
    upper_green = np.array([H_High, S_High, V_High])

    img = ColorDetector(img_copy, lower_green, upper_green)

原图
python opencv选取特定颜色区域_第1张图片
提取特定颜色
python opencv选取特定颜色区域_第2张图片

你可能感兴趣的:(python,opencv,python,计算机视觉,颜色提取)