本教程我将分享几个简单步骤解释如何使用OpenCV进行Python对象计数。
需要安装一些软件:
Python 3
OpennCV
1.了解Opencv从摄像头获得视频的Python脚本import cv2, time#1. Create an object.Zero for external cameravideo=cv2. VideoCapture(0)#1. a variablea=0while True:a=a+1#3. Create frame objectcheck, frame = video.read()print(check)print(frame) # Reprsenting image#6. converting to grascalegray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#4. shadow the framecv2.imshow("Capturing", gray)#5. for press any key to out (milisecond)#cv2.waitKey(0)#7. for playingkey=cv2.waitKey(1)if key==ord('q'):breakprint (a)#2. Shutdown the cameravideo.release() cv2.destroyAllWindows
2.加载视频
现在我们将开始逐步学习这个车辆计数教程。第一步是打开我们将在本教程中使用的视频录制。Python示例代码如下:
import numpy as npimport cv2cap = cv2.VideoCapture('traf.mp4') #Open video filewhile(cap.isOpened()): ret, frame = cap.read() #read a frame try: cv2.imshow('Frame',frame) except: #if there are no more frames to show... print('EOF') break #Abort and exit with 'Q' or ESC k = cv2.waitKey(30) & 0xff if k == 27: breakcap.release() #release video filecv2.destroyAllWindows() #close all openCV windows
3. 在视频窗口中绘图
这部分非常简单,因为我们只在视频上显示文字或画线。
使用Python代码在视频文件中显示文本如下:
import numpy as npimport cv2cap = cv2.VideoCapture('traf.mp4') #Open video filew = cap.get(3) #get widthh = cap.get(4) #get heightmx = int(w/2)my = int(h/2)count = 0while(cap.isOpened()): ret, frame = cap.read() #read a frame try: count = count + 1 text = "Statistika UII " + str(count) cv2.putText(frame, text ,(mx,my),cv2.FONT_HERSHEY_SIMPLEX ,1,(255,255,255),1,cv2.LINE_AA) cv2.imshow('Frame',frame) except: #if there are no more frames to show... print('EOF') break #Abort and exit with 'Q' or ESC k = cv2.waitKey(30) & 0xff if k == 27: breakcap.release() #release video filecv2.destroyAllWindows() #close all openCV windows
除了显示文字,我们还可以绘制线条,圆圈等。OpenCV有许多绘制几何形状的方法
import numpy as npimport cv2cap = cv2.VideoCapture('traf.mp4') #Open video filewhile(cap.isOpened()):