face_recog.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #coding=utf-8
3 import numpy as np
4 import cv2, os, time, base64, urllib2, rospy
5 from json import *
6 # ros msg
7 from xbot_face.msg import FaceResult
8 from std_msgs.msg import String, UInt32
9 from sensor_msgs.msg import Image
10 from cv_bridge import CvBridge, CvBridgeError
11 #人脸识别盒子的IP地址以及接口,详见doc中的天眼魔盒API文档
12 url = "http://192.168.8.141:8000/recognition"
13 
14 
15 
16 class face_recog():
17  """docstring for face_recog"""
18  def __init__(self):
19 # 声明节点订阅与发布的消息
20  self.face_result_pub = rospy.Publisher('/xbot/face_result',FaceResult,queue_size=1)
21  rospy.Subscriber('/xbot/camera/image', Image, self.imageCB)
22  self.bridge = CvBridge()
23  rospy.spin()
24 
25 
26 
27 
28  def imageCB(self, msg):
29  try:
30  cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
31  except CvBridgeError as e:
32  print(e)
33 
34  result_msg = FaceResult()
35  cv2.imwrite('tmp.jpg',cv_image)
36  with open("tmp.jpg", "rb") as fp:
37  image_binary = fp.read()
38  image_binary = base64.b64encode(image_binary)
39  post_data = {"Image":image_binary}
40  body = JSONEncoder().encode(post_data)
41  req = urllib2.Request(url, body)
42  response = urllib2.urlopen(req).read()
43  body = JSONDecoder().decode(response)
44  # rospy.loginfo(body)
45 # 如果没有检测到人脸,人脸次数重置,
46  # rospy.logwarn(body)
47  if body['Id'] == 'UNKNOWN' or body['Id'] == 'None':#no people in frame
48  result_msg.face_exist = 0
49  result_msg.name = body['Id']
50  result_msg.confidence = 0
51  self.face_result_pub.publish(result_msg)
52 
53 # 检测到已注册人脸,人脸次数+1,继续,连续累积次数(中间不出现重置)大于10则确认该识别结果
54  else:#registered people in frame
55  result_msg.face_exist = 1
56  result_msg.name = body['Id']
57  result_msg.confidence = body['Confidence']
58  self.face_result_pub.publish(result_msg)
59  # detected face, but not registered face
60  # else:
61  # result_msg.face_exist = 1
62  # result_msg.name = 'unknown'
63  # result_msg.confidence = body['Confidence']
64  # self.face_result_pub.publish(result_msg)
65 
66 
67 
68 
69 if __name__ == '__main__':
70  rospy.init_node('face_recog')
71  try:
72  rospy.loginfo('face recogition initialized...')
73  face_recog()
74  except rospy.ROSInterruptException:
75  rospy.loginfo('face recogition initialize failed, please retry...')
76 
def imageCB(self, msg)
Definition: face_recog.py:28


xbot_face
Author(s):
autogenerated on Sat Oct 10 2020 03:27:46