1、前言
本文是《人脸识别实战》系列文章的第三篇,主要描述如何实现一个简单的测试客户端跟我们实现的人脸识别服务器进行交互。
人脸识别实战项目的源码地址为:
https://github.com/Oreobird/face_id.git
2、类图设计
我们将以python来实现客户端的简单逻辑,首先定义一个Connection类,负责管理网络连接与数据的收发,然后定义一个Client线程类用于封装一些业务流程的处理,同时也作为一个基类,当需要处理具体的业务逻辑时,再继承这个基类,并实现其中的抽象接口。我们要实现一个实时视频人脸识别的测试客户端RealTimeTester,继承Client基类需要实现do_task(),pre_run()以及post_run()三个方法,具体的类图如下所示:
3、代码实现
RealTimeTester类的代码实现,主要处理的业务包括:
- 在pre_run()中通过opencv打开摄像头并设置图像参数
- 在do_task()中读取摄像头数据,为了实时的性能,先把原始图像尺寸缩小,然后通过cv2.imencode()将图像数据编码为二进制数据,并以base64的编码方式嵌入到Json数据中(具体数据格式参看【人脸识别实战二】服务器端设计与实现 中的2.2小节),然后通过tcp发送Json数据并处理服务器端返回的Json数据,其中的add_overlays()会根据返回的box数据(即人脸框左上、右下坐标与宽高的比例)按比例扩大,最后在原始图像上画出人脸框。
- 在post_run()中简单计算程序结束后识别的准确率。
RealTimeTester类实现代码如下,完整的代码实现在源码目录face_idsrcest中:
class RealTimeTester(client.Client): def __init__(self, ip="", port=1000, resolution=(160, 120), test_user="tester"): client.Client.__init__(self, conn=None, ip=ip, port=port) self.img_param = [] self.camera = None self.resolution = resolution self.test_user = test_user self.correct = 0 self.total = 0 def add_overlays(self, frame, name, box): width, height, _ = frame.shape x1 = int(height * box[0]) y1 = int(width * box[1]) x2 = int(height * box[2]) y2 = int(width * box[3]) cv2.rectangle(frame, (x1, y1), (x2, y2),(0, 255, 0), 2) cv2.putText(frame, name, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), thickness=2, lineType=2) def do_task(self): ret, img = self.camera.read() if ret: cpy_img = img.copy() # cpy_img = cv2.cvtColor(cpy_img, cv2.COLOR_BGR2RGB) cpy_img = cv2.resize(cpy_img, self.resolution) _, img_encode = cv2.imencode('.jpg', cpy_img, self.img_param) img_str = base64.b64encode(img_encode).decode('utf-8') json_data = [{'id': 'xxx', 'name': 'xxx', 'type': 0, 'detect_in_client': False, 'mode': 0, 'img_data': img_str}] self.send_jn_data(json_data) ret, recv_data = self.recv_jn_data() if ret: if recv_data['err_code'] == 0: self.total += 1 user_name = recv_data['user_name'] box = recv_data['box'] print("name: {}, box: {}".format(user_name, box)) if user_name == self.test_user: self.correct += 1 self.add_overlays(img, user_name, box) cv2.imshow("video", img) if cv2.waitKey(1) == ord('q') or self.total == 10000: return False return True def pre_run(self): self.camera = cv2.VideoCapture(0) self.img_param = [int(cv2.IMWRITE_JPEG_QUALITY), 100] # 设置传送图像格式、帧数 time.sleep(0.5) def post_run(self): accuracy = self.correct / self.total print("otal:{}, correct:{}, accuracy:{}".format(self.total, self.correct, accuracy))if __name__ == '__main__': tester = RealTimeTester(ip = '127.0.0.1', port = 8080, test_user='AIPlayer') tester.setName('realtime_tester') tester.setDaemon(True) tester.start() tester.join()