opencv实战——⼏⼗⾏代码搞定物体识别(0基础!!⼩⽩⼊门学习)
我在前⾯的内容 发布了opencv的⼏个模块(⼈脸识别,颜⾊,形状)
现在我们来⼩练⼿⼀下
Part 1:准备数据
1.准备coco.names
是 coco 数据集的标签信息,可以根据⾃⼰类别进⾏修改
2.准备训练好的模型(后续我们可以训练⾃⼰的模型)
这⾥是ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt
3.准备权重
frozen_inference_graph.pb
Part 2: 主函数
import numpy as np
import cv2
thres =0.5# Threshold to detect object
nms_threshold =0.2#(0.1 to 1) 1 means no suppress , 0.1 means high suppress '''
读取摄像头
rectangle函数opencv'''
cap = cv2.VideoCapture(0)#这⾥也可以换成视频路径
cap.set(cv2.CAP_PROP_FRAME_WIDTH,1000)#width
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,1000)#height
cap.set(cv2.CAP_PROP_BRIGHTNESS,150)#brightness
'''
读取分类
'''
classNames =[]
with open('coco.names','r')as f:
classNames = f.read().splitlines()#按⾏拆分
print(classNames)
'''
识别字体颜⾊
'''
font = cv2.FONT_HERSHEY_PLAIN
Colors = np.random.uniform(0,255, size=(len(classNames),3))
'''
构建⽹络
'''
weightsPath ="frozen_inference_graph.pb"
configPath ="ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt"
net = cv2.dnn_DetectionModel(weightsPath,configPath)
net.setInputSize(320,320)
net.setInputScale(1.0/127.5)
net.setInputMean((127.5,127.5,127.5))
net.setInputSwapRB(True)
'''
识别模块
'''
while True:
success,img = ad()
classIds, confs, bbox = net.detect(img,confThreshold=thres)
bbox =list(bbox)
confs =list(np.array(confs).reshape(1,-1)[0])
confs =list(map(float,confs))
#print(type(confs[0]))
#print(confs)
indices = cv2.dnn.NMSBoxes(bbox,confs,thres,nms_threshold)
if len(classIds)!=0:
for i in indices:
i = i[0]
box = bbox[i]
confidence =str(round(confs[i],2))
color = Colors[classIds[i][0]-1]
x,y,w,h = box[0],box[1],box[2],box[3]
cv2.putText(img, classNames[classIds[i][0]-1]+" "+confidence,(x+10,y+20), font,1,color,2)
cv2.imshow("Output",img)
if cv2.waitKey(1)&0xFF==ord('q'):break
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论