没有环境的看这:链接: Anaconda+Jupyter+Opencv+tensorflow安装.
打开Jupyter:
注意:因为我们要做图像处理,我希望你需要处理的图像、视频和程序保存在同一位置。
比如:
准备工作:
数据集下载.
weights解压后:
config也和你的程序文件放在同一文件夹里。同时将你要测试的图片也放在同一文件夹。
在同一文件夹里新建一个.txt
文件,将标签.里的80项内容复制进去。
如:
准备工作就绪,下面敲代码:
声明:
加载tensorflow的预训模型
设置参数:
加载一个图片:
格式设置及输出:
结果:
视频演示:
代码:
cap=cv2.VideoCapture('2021-04-03_231144.mp4')
if not cap.isOpened():
cap=cv2.VideoCapture(0)
if not cap.isOpened():
raise IOError('Can not open video')
font_scale=1#字体大小
font=cv2.FONT_HERSHEY_TRIPLEX#字体类型
while True:
ret,frame=cap.read()
ClassIndex,confidece,bbox=model.detect(frame,confThreshold=0.55)
print(ClassIndex)
if (len(ClassIndex)!=0):
for ClassInd,conf,boxes in zip(ClassIndex.flatten(),confidece.flatten(),bbox):
if(ClassInd<=80):
cv2.rectangle(frame,boxes,(0,0,255),2) #(颜色-红,比例)
cv2.putText(frame,classLabels[ClassInd-1],(boxes[0]+10,boxes[1]+40),font,fontScale=font_scale,color=(0,255,0),thickness=3)
cv2.imshow('Object detection test',frame)
if cv2.waitKey(2) & 0xFF==ord('q'):
break
cap.replease()
cv2.destroyAllwimdows()
结果是视频,我展示一下部分截图:
实时摄像头:
代码:
cap=cv2.VideoCapture(1)
if not cap.isOpened():
cap=cv2.VideoCapture(0)
if not cap.isOpened():
raise IOError('Can not open Camera')
font_scale=1#字体大小
font=cv2.FONT_HERSHEY_TRIPLEX#字体类型
while True:
ret,frame=cap.read()
ClassIndex,confidece,bbox=model.detect(frame,confThreshold=0.55)
print(ClassIndex)
if (len(ClassIndex)!=0):
for ClassInd,conf,boxes in zip(ClassIndex.flatten(),confidece.flatten(),bbox):
if(ClassInd<=80):
cv2.rectangle(frame,boxes,(0,0,255),2) #(颜色-红,比例)
cv2.putText(frame,classLabels[ClassInd-1],(boxes[0]+10,boxes[1]+40),font,fontScale=font_scale,color=(0,255,0),thickness=3)
cv2.imshow('Object detection test',frame)
if cv2.waitKey(2) & 0xFF==ord('q'):
break
cap.replease()
cv2.destroyAllwimdows()
结果: