opencv识别特定颜色(任意照片)

opencv识别特定颜色(任意照片)_第1张图片
opencv识别特定颜色(任意照片)_第2张图片

# 识别特定的颜色
# 识别特定的颜色
import cv2 as cv
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import filedialog
import numpy as np

root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
img = cv.imread(file_path)

img2 = cv.cvtColor(img, cv.COLOR_BGR2HSV)  # 转换BGR色彩空间到HSV色彩空间
lower_hsv = np.array([100, 43, 46])
upper_hsv = np.array([124, 255, 255])
mask = cv.inRange(img2, lower_hsv, upper_hsv)  # cv.inRange()函数的作用是提取想要的颜色,并把该颜色的区域设置为白色,其余的设置为黑色
cnts1, hierarchy1 = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)  # 轮廓检测


for cnt in cnts1:
    (x, y, w, h) = cv.boundingRect(cnt)  # 该函数返回矩阵四个点
    cv.rectangle(img, (x, y - 20), (x + w, y + h), (0, 0, 255), 2)  # 将检测到的颜色框起来

plt.subplot(121), plt.imshow(img)
plt.title('Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(mask)
plt.title('Find_red Image'), plt.xticks([]), plt.yticks([])
plt.show()

根据hsv表格,改变数组上下限,即可取出想要的颜色

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