使用到的库
好多人都想了解一下如何对摄像头进行调用,然后进行目标检测,于是我做了这个小BLOG。
opencv-python==4.1.2.30
Pillow==6.2.1
numpy==1.17.4
这些都是通用的库,版本不同问题应该也不大。
实现思路
利用opencv调用摄像头,读取每一帧传入目标检测网络检测,将检测结果呈现。
由于本文所用的检测格式为RGB格式,CV2读取的时候会使用BGR格式,因此在检测的时候要利用cv2.cvtColor进行转换。
实现代码
以Retinanet为例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
from keras.layers import Input from retinanet import Retinanet from PIL import Image import numpy as np import cv2 retinanet = Retinanet() # 调用摄像头 capture = cv2.VideoCapture( 0 ) while ( True ): # 读取某一帧 ref,frame = capture.read() # 格式转变,BGRtoRGB frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) # 转变成Image frame = Image.fromarray(np.uint8(frame)) # 进行检测 frame = np.array(retinanet.detect_image(frame)) # RGBtoBGR满足opencv显示格式 frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR) cv2.imshow( "video" ,frame) c = cv2.waitKey( 30 ) & 0xff if c = = 27 : capture.release() break retinanet.close_session() |
2020/4/26更新:FPS计算
很多小伙伴说到想要获取FPS,于是给所有的目标检测网络加上了FPS的功能,需要的小伙伴请重新下载。
FPS记录的原理
FPS简单来理解就是图像的刷新频率,也就是每秒多少帧。
假设目标检测网络处理1帧要0.02s。
此时FPS就是50。
FPS实现代码
该代码以ssd为例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#-------------------------------------# # 调用摄像头检测 #-------------------------------------# from ssd import SSD from PIL import Image import numpy as np import cv2 import time ssd = SSD() # 调用摄像头 capture = cv2.VideoCapture( 0 ) # capture=cv2.VideoCapture("1.mp4") fps = 0.0 while ( True ): t1 = time.time() # 读取某一帧 ref,frame = capture.read() # 格式转变,BGRtoRGB frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) # 转变成Image frame = Image.fromarray(np.uint8(frame)) # 进行检测 frame = np.array(ssd.detect_image(frame)) # RGBtoBGR满足opencv显示格式 frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR) fps = ( fps + ( 1. / (time.time() - t1)) ) / 2 print ( "fps= %.2f" % (fps)) frame = cv2.putText(frame, "fps= %.2f" % (fps), ( 0 , 40 ), cv2.FONT_HERSHEY_SIMPLEX, 1 , ( 0 , 255 , 0 ), 2 ) cv2.imshow( "video" ,frame) c = cv2.waitKey( 30 ) & 0xff if c = = 27 : capture.release() break |
以上就是python利用opencv调用摄像头实现目标检测的详细内容,更多关于python opencv调用摄像头目标检测的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/weixin_44791964/article/details/104839376