image.png
    下面是一个人脸识别的完整例子,包括找脸、注册脸、识别脸等全过程。100行代码,其中自动生成代码60行,自己写的代码不到40行,搞定人脸识别。

    1. from cvs import *
    2. import facerecognition
    3. import numpy as np
    4. #这个类是界面类,是自动生成的代码,通过wizard工具自动生成。
    5. class MyApp(App):
    6. def __init__(self, *args):
    7. super(MyApp, self).__init__(*args)
    8. def main(self):
    9. #creating a container VBox type, vertical (you can use also HBox or Widget)
    10. main_container = gui.VBox(width=360, height=680, style={'margin':'0px auto'})
    11. #添加一个摄像头
    12. self.aidcam = OpencvVideoWidget(self, width=340, height=480)
    13. self.aidcam.style['margin'] = '10px'
    14. self.aidcam.set_identifier("myimage_receiver")
    15. main_container.append(self.aidcam)
    16. #添加一个输入框
    17. self.txt = gui.TextInput(width=200, height=30, margin='10px')
    18. self.txt.set_text('usename')
    19. #给输入框添加一个事件
    20. self.txt.onchange.do(self.on_text_area_change)
    21. #添加一个注册按钮
    22. self.bt = gui.Button('Add Person!', width=200, height=30, margin='10px')
    23. # setting the listener for the onclick event of the button
    24. #给这个按钮添加一个事件
    25. self.bt.onclick.do(self.on_button_pressed)
    26. main_container.append(self.txt)
    27. main_container.append(self.bt)
    28. # returning the root widget
    29. return main_container
    30. def on_text_area_change(self, widget, newValue):
    31. print('Text Area value changed!')
    32. def on_button_pressed(self, widget):
    33. userId = self.txt.get_text()
    34. cvs.setLbs(userId)
    35. self.bt.set_text('success!')
    36. #这个是每一帧的处理函数
    37. def process():
    38. cap=cvs.VideoCapture(1)
    39. #加载模型
    40. facerecog = facerecognition.FaceRecognition("./models", 0.73)
    41. while True:
    42. sleep(30)
    43. img =cap.read()
    44. if img is None :
    45. continue
    46. image_char = img.astype(np.uint8).tostring()
    47. userId=cvs.getLbs()
    48. if userId!='':
    49. #注册一张人脸
    50. ret=facerecog.add_person(userId, img.shape[0], img.shape[1], image_char)
    51. if ret==0:
    52. print ('you add_person is success!')
    53. # cvs.setMsg_status(1)
    54. else :
    55. print ('you add_person is failed!')
    56. userId=''
    57. cvs.setLbs(userId)
    58. continue
    59. #识别一张脸
    60. rets = facerecog.recognize(img.shape[0], img.shape[1], image_char)
    61. #print 'rets:',rets
    62. for ret in rets:
    63. #for ret in each:
    64. print ('draw bounding box for the face',ret)
    65. rect = ret['rect']
    66. p1 = (int(rect[0]), int(rect[1]))
    67. p2 = (int(rect[0]+rect[2]), int(rect[1]+rect[2]))
    68. #draw rect,names of faces
    69. cv2.rectangle(img, p1,p2, (0, 255, 0) , 3, 1)
    70. cv2.putText(img, ret['name'], (int(rect[0]), int(rect[1])-30),cv2.FONT_ITALIC, 2, (77, 255, 9), 2)
    71. cvs.imshow(img)
    72. if __name__ == '__main__':
    73. initcv(process)
    74. startcv(MyApp)

    Aid内置了大量的AI深度学习的例子,请参考:
    image.png