二、使用步骤
1.引入库
import cv2
import numpy as np
def color_detect(img, x_min, y_min, x_max, y_max):
# r 0-15
# y 16-30
# g 35-60
# b 70-115
# p 130-160
c_count = [0, 0, 0, 0, 0]
m=img[y_min:y_max, x_min:x_max]
# m = cv2.cvtColor(m, cv2.COLOR_BGR2HSV)
m = np.reshape(m, (-1, 3), order='F')
i = 0
for i in range(m.shape[0]):
# print(m[i])
if m[i, 1]>40 :
if m[i, 0] <= 15 or m[i, 0] > 175:
c_count[0] = c_count[0] + 1
elif m[i, 0] > 15 and m[i, 0] <= 30:
c_count[1] = c_count[1] + 1
elif m[i, 0] > 35 and m[i, 0] <= 60:
c_count[2] = c_count[2] + 1
elif m[i, 0] > 70 and m[i, 0] <= 115:
c_count[3] = c_count[3] + 1
elif m[i, 0] > 130 and m[i, 0] <= 175:
c_count[4] = c_count[4] + 1
print(c_count)
c_index=c_count.index(max(c_count))
c_str=''
if c_index==0:
c_str='r'
elif c_index==1:
c_str ='y'
elif c_index == 2:
c_str = 'g'
elif c_index == 3:
c_str = 'b'
elif c_index == 4:
c_str = 'p'
print(c_str)
print(np.mean(m, 0))
image=cv2.imread('3.jpg')
image = cv2.resize(image, (640, 360))
HSV=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
def getpos(event,x,y,flags,param):
if event==cv2.EVENT_LBUTTONDOWN: #定义一个鼠标左键按下去的事件
print(HSV[y,x])
color_detect(HSV, 250, 150, 400, 180)
# print(np.mean(np.reshape(HSV[150:180, 250:400], (-1, 3), order='F'), 0))
#cv2.rectangle(HSV, (250, 150), (400, 180), (0, 0, 255), 2)
cv2.imshow("imageHSV",HSV)
cv2.imshow('image',image)
cv2.setMouseCallback("imageHSV",getpos)
cv2.waitKey(0)
low_hsv = np.array([110, 120, 3])
high_hsv = np.array([126, 255, 20])
import cv2
import numpy as np
import threading
import time,os
import pyautogui as pag
area = 0
cap = cv2.VideoCapture(0) # 打开摄像头
aaaaa=0
bbbb=1
def getpos(event,x,y,flags,param):
global aaaaa
if event==cv2.EVENT_LBUTTONDOWN: #定义一个鼠标左键按下去的事件
aaaaa=1
while True:
ret, frame = cap.read() # 读取摄像头
cv2.imshow("mask",frame)
cv2.setMouseCallback("mask",getpos)
if aaaaa==1:
print("catcat")
path="./pic/"+str(bbbb)+".jpg"
cv2.imwrite(path,frame)
aaaaa=0
bbbb=bbbb+1
if cv2.waitKey(1) & 0xFF == ord('q'): # 按q退出
break
cap.release()
cv2.destroyAllWindows()
# 距离的判断根据色块的大小
# 判断色块位置图像侵占