Never too late to learn.

0%

树莓派Raspberry Pi3 + OpenCV实现动态人脸捕捉并post到web服务器

硬件:

  • 树莓派Raspberry Pi3
  • USB网络摄像头

软件:

  • 树莓派ubuntu 操作系统
  • python2.7

人脸识别使用OpenCV python 开源项目,上传使用Requests上传文件至服务器

python 代码如下:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#coding=utf-8
import numpy as np
import cv2
import cv2.cv as cv
import requests
import threading

def detect(img, cascade):
rects = cascade.detectMultiScale(img, scaleFactor=1.3,
minNeighbors=5, minSize=(30, 30), flags = cv.CV_HAAR_SCALE_IMAGE)
if len(rects) == 0:
return []
print rects
rects[:,2:] += rects[:,:2]
print rects
return rects

#在img上绘制矩形
def draw_rects(img, rects, color):
for x1, y1, x2, y2 in rects:
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)



def upload_images():
print 'uploading...'

#cv2.imshow('upload_img', cv2.imread('img.png',0))
cv2.imwrite("img.jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 59])
r = requests.post(url, files = {'image': open('img.jpg', 'rb')})

#cv2.imwrite('img.png',frame, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
#r = requests.post(url, files = {'image': open('img.png', 'rb')})

print(r.text)

global timer
timer = threading.Timer(5, upload_images)
timer.start()

url = 'your url here'

cap = cv2.VideoCapture(0)
print cap.get(3)
print cap.get(4)
fps = cap.get(cv2.cv.CV_CAP_PROP_FPS) # 获取原视频帧率
print 'fps:'
print fps

timer = threading.Timer(5, upload_images)
timer.start()

while(True):
# Capture frame-by-frame
ret, frame = cap.read()
#ret = cap.set(3,320)
#ret = cap.set(4,240)
cv2.imshow('camera',frame)

# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#raw = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

# Display the resulting frame
# cv2.imshow('frame',gray)

#直方图均衡处理
gray = cv2.equalizeHist(gray)
#脸部特征分类地址
cascade_fn = '/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml'

#读取分类器,CascadeClassifier下面有一个detectMultiScale方法来得到矩形
cascade = cv2.CascadeClassifier(cascade_fn)

#通过分类器得到rects
rects = detect(gray, cascade)

if (len(rects)) :
#画矩形
print 'face_detected'
vis = frame.copy()
draw_rects(vis, rects, (0, 255, 0))
cv2.imshow('face_detected', vis)
#cv2.imshow('upload_img', cv2.imread('img.png',0))
cv2.imwrite("img.jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 59])
r = requests.post(url, files = {'image': open('img.jpg', 'rb')})

#cv2.imwrite('img.png',frame, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
#r = requests.post(url, files = {'image': open('img.png', 'rb')})

print(r.text)
#upload_images()

if cv2.waitKey(1) & 0xFF == ord('q'):
break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Coffee? ☕