红绿灯识别1
步骤
- 高斯模糊
- 边缘提取
- 膨胀腐蚀
- 中值滤波
- 再次膨胀
- 霍夫圆环检测区域
- 将图片从BGR格式转换为HSV格式
- 设计颜色阈值
- 中值滤波
- 统计像素点数
import cv2
import numpy as np
COLOERS = {'red': (0, 0, 255),'green': (0, 255, 0),'yellow': (0, 255, 255),
}
def detect_color(img):hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)min_hsv_red1 = np.array([0, 100, 100])max_hsv_red1 = np.array([10, 255, 255])min_hsv_red2 = np.array([160, 100, 100])max_hsv_red2 = np.array([179, 255, 255])min_hsv_yellow = np.array([20, 5, 150])max_hsv_yellow = np.array([30, 255, 255])min_hsv_green = np.array([35, 5, 150])max_hsv_green = np.array([90, 255, 255])thresh_red = cv2.inRange(hsv, min_hsv_red1, max_hsv_red1) + cv2.inRange(hsv, min_hsv_red2, max_hsv_red2)thresh_yellow = cv2.inRange(hsv, min_hsv_yellow, max_hsv_yellow)thresh_green = cv2.inRange(hsv, min_hsv_green, max_hsv_green)red_blur = cv2.medianBlur(thresh_red, 5)yellow_blur = cv2.medianBlur(thresh_yellow, 5)green_blur = cv2.medianBlur(thresh_green, 5)red = cv2.countNonZero(red_blur)yellow = cv2.countNonZero(yellow_blur)green = cv2.countNonZero(green_blur)lights_color = max(red,yellow,green)if lights_color > 60:if lights_color == red:return 'red'elif lights_color == yellow:return 'yellow'elif lights_color == green:return 'green'if __name__ == '__main__':cap = cv2.VideoCapture('lights1.jpeg')while True:ret,frame = cap.read()if ret == False:breakimage = cv2.GaussianBlur(frame, (3, 3), 0)cv2.imshow("gs", image)image_Canny = cv2.Canny(image, 50, 100)cv2.imshow('01', image_Canny)kernalX = cv2.getStructuringElement(cv2.MORPH_RECT, (8, 3))kernalY = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 8))image_Canny = cv2.dilate(image_Canny, kernalX)image_Canny = cv2.erode(image_Canny, kernalX, iterations=4)image_Canny = cv2.dilate(image_Canny, kernalY)image_Canny = cv2.erode(image_Canny, kernalY, iterations=4)cv2.imshow('02', image_Canny)image_blur = cv2.medianBlur(image_Canny, 25)cv2.imshow('image_blur', image_blur)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (35, 35))image_blur = cv2.dilate(image_blur, kernel)cv2.imshow('dilate', image_blur)circle = cv2.HoughCircles(image_blur, cv2.HOUGH_GRADIENT, 1, 40, param1=20, param2=10, minRadius=30, maxRadius=60)if not circle is None:circle = np.uint16(np.around(circle))for i in circle[0, :]:x, y, r = i[0], i[1], i[2]cropped_circle = frame[y - r:y + r, x - r:x + r]color = detect_color(cropped_circle)cv2.putText(frame, color, (x-r, y-r-5), cv2.FONT_HERSHEY_COMPLEX, 1, COLOERS[color], 2)cv2.circle(frame, (i[0], i[1]), i[2], COLOERS[color], 2)cv2.imshow("circle", frame)cv2.waitKey(0)
测试原图: