检测行人数目
import cv2 import time import numpy as np import pymysql import datetime def get_people_num(max_num): capture=cv2.VideoCapture("acvis09-5950.AVI")#打开本机摄像头 classifier=cv2.CascadeClassifier('cascades.xml')#加载分类器 color=(0,255,0) '''connect = pymysql.Connect(#连接到数据库 host='192.168.43.86', port=3306, user='root', password='root', db='mydb', charset='utf8' )''' place="****" # 生成游标对象 #cursor = connect.cursor() while(True):#获取每一帧q ret,frame=capture.read()#读取当前图像 gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#灰度化处理 people_num=0#定义本次图片中的人数 time.sleep(5)#休眠一秒,减少运算负担 blur = cv2.GaussianBlur(gray, (5, 5), 0)#高斯模糊 kernel = np.ones((5, 5), np.uint8) erosion = cv2.erode(blur, kernel, iterations=1)#腐蚀 faceRects = classifier.detectMultiScale(erosion, scaleFactor=1.2, minNeighbors=3,minSize=(32, 32)) # 将人脸所有圈起来形成一个集合 for faceRect in faceRects: x,y,w,h=faceRect people_num+=1 cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) font = cv2.FONT_HERSHEY_SIMPLEX # 获取内置字体 # 调用函数,对人脸坐标位置,添加一个(x+30,y+30)的矩形框用于显示当前捕捉到了多少人脸图片 cv2.putText(frame, ('%d' % people_num), (x + 30, y + 30), font, 1, (255, 0, 255), 4) cv2.imshow('frame', frame) now=str(datetime.datetime.now()) findsql="SELECT THRESHOLD FROM HUMANTRAFFIC WHERE SITE='%s'"%("KOI") out=cursor.execute(findsql) print(cursor.fetchone()) max_num=int(cursor.fetchone()[0]) print(max_num) if people_num>8: print(now[0:19]) sql_insert = """INSERT INTO ALARM(SITE,TIME,NUM) VALUES (%s, %s,%s)""" result = cursor.executemany(sql_insert, [("KOI",now[0:19],str(people_num))]) print(result) print("超过最大阈值人数%d人"%(max_num)) update_sql = "UPDATE HUMANTRAFFIC SET LAST_UPDATED='%s', STATE='%s', NUM='%s' WHERE SITE='%s'" % ( #now[0:19], "异常", str(people_num), "KOI") print(update_sql) cursor.execute(update_sql) connect.commit() else: update_sql = "UPDATE HUMANTRAFFIC SET LAST_UPDATED='%s', STATE='%s', NUM=%s WHERE SITE='%s'" % ( now[0:19],"正常",str(people_num),"KOI") print(update_sql) cursor.execute(update_sql) connect.commit() c = cv2.waitKey(10) if c & 0xFF == ord('q'): break capture.release() # 释放摄像头并销毁所有窗口 cv2.destroyAllWindows() # 销毁所有的窗口 print('Finished.') def main(): get_people_num(8) main()