使用 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: 33[31m
#Green: 33[1;32;40m
#Reset color: 33[0;37;40m
print('33[1;32;40mHello everyone.33[0;37;40m')
print("33[31mBrooo this is red and so susy i think.33[0;37;40mn")

最新更新