import cv2
import numpy as np
#颜色色值
list = [[['红色'],[0,43,46],[10,255,255]],
[['红色'],[156,43,46],[180,255,255]],
[['蓝色'],[100,43,46],[124,255,255]],
[['黄色'],[26,43,46],[34,255,255]],
[['白色'],[0,0,221],[180,30,255]],
[['黑色'],[0,0,0],[180,25,46]],
[['橙色'],[11,43,46],[25,255,255]],
[['绿色'],[35,43,46],[77,255,255]]]
Mouse_xy = ['','']
#导入图像
img = cv2.imread('www.jpg')
out = img.copy()
img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
v = cv2.Canny(img,100,500)#边缘识别
cv2.imshow('out',out)
#检测
#圆形识别
c = cv2.HoughCircles(v,cv2.HOUGH_GRADIENT,dp=1, minDist=300, circles=255, param1=1300, param2=20, minRadius=50,maxRadius=0)
if c is not None:
print('=', c)
#c = np.round(c[0, :]).astype("int")
c = c[0]
print(c)
#多边形检测
cnt,lib = cv2.findContours(v,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
def color():
color1 = out.copy()
def get_moues( a, x, y, f, p):
Mouse_xy[0] = x
Mouse_xy[1] = y
color2 = color1[y-25:y+25,x-25:x+25]
cv2.imshow('color',color2)
color, m, area = '', 0, 0
for l in list:
hsv = cv2.cvtColor(color2, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, np.array(l[1]), np.array(l[2]))
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
for cnt in range(len(cnts)):
area = cv2.contourArea(cnts[cnt])
if area > m:
color = l[0][0]
m = area
print('color=', color)
Mouse = cv2.setMouseCallback('out', get_moues)
def OUT():#绘制
try:
for (x,y,r) in c:
x = int(x)
y = int(y)
r = int(r)
print('x=', x, 'y=', y, 'r=', r)
cv2.circle(out, (x, y), r, (0, 255, 0), 3)
cv2.circle(out,(x,y),r-r+1,(255,255,0),3)
cv2.putText(out,"circle",(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0))
except TypeError:
print('没有圆')
def OUT_S():
i=1
R = 0
G = 0
print (len(lib[0]))
while i<len(lib[0]):
c = 0.01 * cv2.arcLength(cnt[i], True)
point = cv2.approxPolyDP(cnt[i], c, True)
if len(point)<=6 and len(point)>2:
cv2.drawContours(out,cnt,i,(R,G,255),2)
#print('当前图形的顶点有',len(point))
#print('point=',type(point))
x,y = point[0][0]
print('x=',x,'y=',y)
if len(point) == 3:
cv2.putText(out,'3',(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0))
if len(point) == 4:
cv2.putText(out,'4',(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0))
if len(point) == 5:
cv2.putText(out, '5', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0))
if len(point) == 6:
cv2.putText(out, '6', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0))
i=i+1
#cv2.imshow('out',out)
OUT()
OUT_S()
color()
cv2.imshow('v',v)
cv2.imshow('out',out)
cv2.waitKey()