基于python的红绿灯识别day2
基于python的红绿灯识别day2
先⽤⼀个简单的⽅法实现红绿灯识别(基于opencv的模板匹配)
1.先使⽤美图秀秀,采集⾜够多的模板⽤于模板匹配
2.使⽤python将图⽚数据按顺序编号
感谢博主做出的贡献blog.csdn/m0_37592397/article/details/80372009
可以使⽤这个代码⽤来给样本数据和模板数据编号
3.使⽤opencv内置函数进⾏模板匹配,通过相似程度检测红绿灯`
import cv2 as cv
import numpy as np
import os
import time
def template_demo():
kernel_sharpen_3 = np.array([
[-1,-1,-1,-1,-1],
[-1,2,2,2,-1],
[-1,2,8,2,-1],
[-1,2,2,2,-1],
[-1,-1,-1,-1,-1]])/8.0#锐化使⽤的内核
filelist = os.listdir("frames") #获取⽂件路径美图秀秀在线使用
total_num = len(filelist)#获取⽂件长度(个数)
methods = [cv.TM_SQDIFF_NORMED]#将模板匹配的⽅法存⼊元组中
same=1#相似程度⼤⼩
for item in range(total_num):
file = "frames\\"+str(item+1)+".jpg"#待检测图⽚路径
target = cv.imread(file)
c=0
print(file)
for md in methods:
targetcopy = np.copy(target)
for i in range(7):
filename = "model\\1."+str(i+1)+".jpg"#模板图⽚路径
tpl = cv.imread(filename)
# print(filename)
b=1
while b:
tpl = cv.filter2D(tpl,-1,kernel_sharpen_3)#利⽤内核实现对图像的卷积运算
result = cv.matchTemplate(targetcopy,tpl,md)#模板匹配
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(result)#相似度,位置
if md == cv.TM_SQDIFF_NORMED:#cv.TM_SQDIFF_NORMED⽅法min_val,min_val越⼩匹配度越好                        tl = min_loc
same = min_val
#  print(min_val)
if same < 0.3:
br1 = (tl[0]+tpl.shape[1],tl[1]+tpl.shape[0])#获得匹配区域
c+=1
else:
b=0
else:#剩下的⽅法max_val,这个越⼤匹配度越好
tl = max_loc
same = max_val
# print(max_val)
if same > 0.9:
br1 = (tl[0]+19,tl[1]+33)
br1 = (tl[0]+19,tl[1]+33)
b=0
# cv.imshow("match"+np.str(md),targetcopy)
print(c)
with open("", 'a') as f:
f.write(file+","+str(c)+"\n\r")
f.close()
template_demo()
cv.waitKey(0)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。