有言在前
是给学弟做工程训练时,我帮着写的色块识别代码,清理库存发现,代码思路很常规的处理,有感兴趣的也别浪费,也算个思路。
Show me the code
import cv2
import numpy as np
def color_classify(srcImg, threshold):
result = []
# 定义颜色范围,这里可以根据自己的需求定义
boundaries = [
([0, 43, 46], [10, 255, 255], "Red")
([35, 43, 46], [77, 255, 255], "Green"),
([100, 43, 46], [124, 255, 255], "Blue")
]
hsv_img = cv2.cvtColor(srcImg, cv2.COLOR_BGR2HSV) # change to hsv model
# 遍历颜色范围
for (lower, upper, color) in boundaries:
# 由颜色范围创建NumPy数组
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")
# get mask
mask = cv2.inRange(hsv_img, lower, upper)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cv2.imshow('Mask', mask)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
if len(cnts) > 0:
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
if radius > threshold:
print("颜色:{0} 半径:{1}".format(color, radius) )
result.append(color)
return result
if __name__ == '__main__':
capture = cv2.VideoCapture(0) # 0是代表摄像头编号,只有一个的话默认为0
while True:
# 调用摄像机
ref, capframe = capture.read()
if ref is True:
# 颜色分类
color_threshold = 150
result = color_classify(capframe, color_threshold)
if len(result) > 0:
print(result)
cv2.putText(capframe, result[0], (20, 60), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
cv2.imshow('frame', capframe)
if cv2.waitKey(15) == 'q':
break
capture.release()
cv2.destroyAllWindows()