需要实现倒车辅助标记检测的功能,倒车辅助标记颜色已经确定了,所以不需要使用深度学习的方法,那样成本太高了,直接可以使用颜色检测的方法。
1.首先需要确定待检测目标的HSV值
import cv2
img = cv2.imread('l3.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
def mouse_click(event, x, y, flags, para):
if event == cv2.EVENT_LBUTTONDOWN:
print('PIX:', x, y)
print("BGR:", img[y, x])
print("GRAY:", gray[y, x])
print("HSV:", hsv[y, x])
if __name__ == '__main__':
cv2.namedWindow("img")
cv2.setMouseCallback("img", mouse_click)
while True:
cv2.imshow('img', img)
if cv2.waitKey() == ord('q'):
break
cv2.destroyAllWindows()
2.然后利用颜色检测,检测出指定目标
import numpy as np
import cv2
font = cv2.FONT_HERSHEY_SIMPLEX
lower_red = np.array([0, 127, 128])
higher_red = np.array([10, 255, 255])
lower_yellow = np.array([15, 230, 230])
higher_yellow = np.array([35, 255, 255])
lower_blue = np.array([85,240,140])
higher_blue = np.array([100,255,165])
frame=cv2.imread("l3.png")
img_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask_red = cv2.inRange(img_hsv, lower_red, higher_red)
mask_yellow = cv2.inRange(img_hsv, lower_yellow, higher_yellow)
mask_yellow = cv2.medianBlur(mask_yellow, 7)
mask_red = cv2.medianBlur(mask_red, 7)
mask_blue = cv2.inRange(img_hsv, lower_blue, higher_blue)
mask_blue = cv2.medianBlur(mask_blue, 7)
print(mask_red)
cnts1, hierarchy1 = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts2, hierarchy2 = cv2.findContours(mask_blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts3, hierarchy3 = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in cnts1:
(x, y, w, h) = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(frame, 'red', (x, y - 5), font, 0.7, (0, 0, 255), 2)
for cnt in cnts2:
(x, y, w, h) = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(frame, 'blue', (x, y - 5), font, 0.7, (0, 0, 255), 2)
for cnt in cnts3:
(x, y, w, h) = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, 'yellow', (x, y - 5), font, 0.7, (0, 255, 0), 2)
cv2.imshow('frame', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
3.效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/54c50d18719d9cdcbca5b4247ee3ec8c.png)