基本思路:
1.用霍夫圆检测 挑选出图片中的圆形区域
2.颜色筛选,挑选出当中的红 绿 黄部分,实现对于交通信号灯的筛选
为演示基本思路 此处以红灯举例进行实战
原图:
检测红灯之后:
开源代码:
import cv2
import numpy as np
font = cv2.FONT_HERSHEY_SIMPLEX
img = cv2.imread(r"C:\Users\WM202\Pictures\4.jpg")#自定义图片路径
GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
GrayImage= cv2.medianBlur(GrayImage,5) #降噪处理
ret,th1 = cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(GrayImage,255,cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,3,5)
th3 = cv2.adaptiveThreshold(GrayImage,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,3,5)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(th2,kernel,iterations=1)
dilation = cv2.dilate(erosion,kernel,iterations=1)
imgray=cv2.Canny(erosion,30,100)
circles = cv2.HoughCircles(imgray,cv2.HOUGH_GRADIENT,1,30,
param1=50,param2=10,minRadius=5,maxRadius=20)
cv2.namedWindow("Original",cv2.WINDOW_NORMAL )
cv2.imshow('Original',img)
cv2.waitKey(0)
#圆形检测完毕
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lower_red1 = np.array([0, 100, 100])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([160, 100, 100])
upper_red2 = np.array([180, 255, 255])
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
maskr = cv2.add(mask1, mask2)
cv2.namedWindow("red",cv2.WINDOW_NORMAL )
cv2.imshow("red", maskr)
cv2.waitKey()
#select the appropriate circle and draw it out
size=img.shape
r=10
bound=4.0/10
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
if i[0]>size [1] or i[1]>size[0] or i[1]>size[0]*bound:
continue
h,s=0.0,0.0
for m in range(-r,r):
for n in range(-r,r):
if(i[1]+m)>=size[0] or(i[0]+n)>=size[1]:
continue
h+=maskr[i[1]+m,i[0]+n]
s+=1
if h/s>50:#The parameter can be adjusted
# draw the outer circle
cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)
cv2.putText(img,'RED',(i[0],i[1]),font,1,(255,0,0),2,cv2.LINE_AA)
cv2.namedWindow("detected results",cv2.WINDOW_NORMAL )
cv2.imshow('detected results',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
感想与总结:
在完成这个项目之前,需要首先了解霍夫圆检测 及其各个函数参数的意义 有意向深入钻研者需要深挖其中数学原理 和几何意义
颜色筛选方面:需要实战几个关于Inrange函数的demo以实现颜色的筛选,再者使用numpy库来划定颜色范围,创建Window使用namedWindow函数,其意义在于创建可以改变大小的窗口,通过缩放功能的创建,适应不同图形的尺寸
一些留下来的思考问题:
关于原图转灰度以后,进行降噪处理,这里采用的是中值滤波,未对其参数与方法有过多调整
一些关于边缘的调整,参数未修改
样本图片较为理想 干扰背景较小