使用 Python 和 OpenCV 进行颜色检测

Color detection using Python & OpenCV

是否可以自定义此代码,以便在框架中存在特定颜色时打印某些内容,或者在框架中未检测到颜色时打印其他内容?如果没有,那我该如何开发这个功能呢?有什么建议么?我只是计算机视觉的初学者 和图像处理。谢谢。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    width = int(cap.get(3))
    height = int(cap.get(4))

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_blue = np.array([90, 50, 50])
    upper_blue = np.array([130, 255, 255])

    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    result = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.imshow('frame', result)
    cv2.imshow('mask', mask)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

我想你可以在你的面具上使用区域道具:

for region in regionprops(mask):
    # take regions with large enough areas
    if region.area >= 20:
        print("color")
    else:
        print("no color")

像这样的东西应该有用。我使用 20 作为区域区域,但您必须根据您的使用情况尝试最佳值。 此代码甚至可以检测存在多少颜色区域

以下可能有效:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    width = int(cap.get(3))
    height = int(cap.get(4))

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    # only one colour in range:
    lower_blue = np.array([90, 50, 50])
    upper_blue = np.array([90, 50, 50])
    included = False
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
    for i in range(mask.shape[0]):
         for j in range(mask.shape[1]):
              if mask[i,j] == 1:
                   included = True

    if included == True:
        print("colour is included")
    else:
        print("colour is not included")
    result = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.imshow('frame', result)
    cv2.imshow('mask', mask)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

你可以这样打印彩色

import os

os.system('')
#Red: [31m
#Green: 3[1;32;40m
#Reset color: 3[0;37;40m

print('3[1;32;40mHello everyone.3[0;37;40m')
print("[31mBrooo this is red and so susy i think.3[0;37;40m\n")