· 4 years ago · Jun 05, 2021, 05:56 AM
1import requests
2import cv2
3import numpy as np
4import time
5from PIL import Image
6import base64
7import io
8from io import BytesIO
9from pprint import pprint
10import smtplib
11from email.mime.text import MIMEText
12api_key = 'o2smMPYhZ564B76u5lQ32iTh'
13secret_key = '7Qq0BfGMMSfBpDpG6uvMy73ydPvQ0nen'
14
15#url = 'rtsp://admin:admin@192.168.0.105:8554/live'
16
17def emailSend(content):
18 #设置服务器所需信息
19 #qq邮箱服务器地址
20 mail_host = 'smtp.qq.com'
21 #qq用户名
22 mail_user = '1909560966@qq.com'
23 #密码(部分邮箱为授权码)
24 mail_pass = 'qqoofpsxsypnbegg'
25 #邮件发送方邮箱地址
26 sender = '1909560966@qq.com'
27 #邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
28 receivers = ['1909560966@qq.com']
29
30 #设置email信息
31 #邮件内容设置
32 mess='当前博物馆人数为'+str(content)+'人,达到峰值'
33 message = MIMEText(mess,'plain','utf-8')
34 #邮件主题
35 message['Subject'] = '博物馆人数预警'
36 #发送方信息
37 message['From'] = sender
38 #接受方信息
39 message['To'] = receivers[0]
40
41 #登录并发送邮件
42 try:
43 smtpObj = smtplib.SMTP()
44 #连接到服务器
45 smtpObj.connect(mail_host,25)
46 #登录到服务器
47 smtpObj.login(mail_user,mail_pass)
48 #发送
49 smtpObj.sendmail(
50 sender,receivers,message.as_string())
51 #退出
52 smtpObj.quit()
53 print('success')
54 except smtplib.SMTPException as e:
55 print('error',e) #打印错误
56
57
58class Traffic_flowRecognizer(object):
59 def __init__(self, api_key, secret_key):
60 self.access_token = self._get_access_token(api_key=api_key, secret_key=secret_key)
61 self.API_URL = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/body_tracking' + '?access_token=' \
62 + self.access_token
63 #获取token
64 @staticmethod
65 def _get_access_token(api_key, secret_key):
66 api = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials' \
67 '&client_id={}&client_secret={}'.format(api_key, secret_key)
68 rp = requests.post(api)
69 if rp.ok:
70 rp_json = rp.json()
71 print(rp_json['access_token'])
72 return rp_json['access_token']
73 else:
74 print('=> Error in get access token!')
75 def get_result(self, params):
76 global person_num
77 rp = requests.post(self.API_URL, data=params)
78 if rp.ok:
79 print('=> Success! got result: ')
80 rp_json = rp.json()
81 #pprint(rp_json)
82 person_num = rp.json().get('person_num')
83 #print(person_num)
84
85 return rp_json
86 else:
87 print('=> Error! token invalid or network error!')
88 print(rp.content)
89 return None
90 #人流量统计
91 def detect(self):
92 global person_num
93 ###对视频进行抽帧后,抽帧频率5fps,连续读取图片
94 camera = cv2.VideoCapture("5.mp4")
95 if (camera.isOpened()):
96 print('Open camera 1')
97 else:
98 print('Fail to open camera 1!')
99 time.sleep(0.05)
100 camera.set(cv2.CAP_PROP_FRAME_WIDTH, 852) # 2560x1920 2217x2217 2952×1944 1920x1080
101 camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
102 camera.set(cv2.CAP_PROP_FPS, 120) # 抽帧参数
103
104 while True:
105 ret, frame = camera.read() # 逐帧采集视频流
106 if frame is not None:
107 image = Image.fromarray(frame)
108 image = image.resize((960, 540))
109 frame = np.array(image)
110 shared_image = frame
111 img = Image.fromarray(shared_image) # 将每一帧转为Image
112 output_buffer = BytesIO() # 创建一个BytesIO
113 img.save(output_buffer, format='JPEG') # 写入output_buffer
114 byte_data = output_buffer.getvalue() # 在内存中读取
115 img_str = base64.b64encode(byte_data) # 转为BASE64
116
117 data_list = []
118 data_list.append(img_str)
119
120 params = {'dynamic':'true','area':'1,1,959,1,959,400,1,400','case_id':1213,'case_init':'false','image':data_list,'show':'true'}
121 tic = time.perf_counter()
122 rp_json = self.get_result(params)
123 toc = time.perf_counter()
124 print('单次处理时长: '+'%.2f' %(toc - tic) +' s')
125 print('当前博物馆人数:',person_num)
126 if person_num>=30:
127 emailSend(person_num)
128
129 img_b64encode = rp_json['image']
130 img_b64decode = base64.b64decode(img_b64encode) # base64解码
131 #显示检测结果图片
132 image = io.BytesIO(img_b64decode)
133 img = Image.open(image)
134 img.show()
135
136if __name__ == '__main__':
137 recognizer = Traffic_flowRecognizer(api_key, secret_key)
138 recognizer.detect()
139
140
141
142
143
144
145
146
147
148