当前位置:   article > 正文

基于opencv的人脸识别和物体检测_opencv物体识别

opencv物体识别

opencv基于haar特征和cascade分类器进行人脸识别,基于R-CNN进行物体识别。

要求:

先看完成情况:

所需python库:获取方式1.win+R-cmd-pip install+库名 

获取方式2.pycharm环境下,File-Settings-Python Interpreter-点击加号进行下载

  1. import cv2
  2. import datetime
  3. import numpy as np
  4. from PIL import Image
  5. import matplotlib.pyplot as plt
  6. import torchvision.transforms as T
  7. import torchvision
  8. import socket
1、人脸识别及储存识别信息:

1.1、训练

要进行特定人脸的识别需要使用若干张照片进行训练,获得训练的数据,再捕捉特定人员的特征进而识别出信息。

  1. import cv2
  2. import os
  3. import numpy as np
  4. from PIL import Image
  5. #训练
  6. def getimagesandlabels(path):
  7. facesamples = []
  8. ids = []
  9. imagepaths = [os.path.join(path, f) for f in os.listdir(path)]
  10. face_detector = cv2.CascadeClassifier('D:\opencv\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
  11. for imagePath in imagepaths:
  12. pil_img = Image.open(imagePath).convert('L')
  13. img_numpy = np.array(pil_img, 'uint8')
  14. id = int(os.path.split(imagePath)[-1].split(".")[0])
  15. faces = face_detector.detectMultiScale(img_numpy) #检测人脸
  16. for(x, y, w, h) in faces:
  17. facesamples.append(img_numpy[y:y+h, x:x+w])
  18. ids.append(id)
  19. return facesamples, ids
  20. if __name__ == '__main__':
  21. path = './train/' #训练使用图片的位置
  22. faces, ids1 = getimagesandlabels(path)
  23. recognizer = cv2.face.LBPHFaceRecognizer_create()
  24. recognizer.train(faces, np.array(ids1))
  25. recognizer.write('trainer/trainer.yml') #保存训练的数据

我获得的训练结果:

1.2人脸识别

调用训练结果进行人脸识别和信息获取,并储存识别时间和人员id。

  1. face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
  2. recognizer = cv2.face.LBPHFaceRecognizer_create()
  3. recognizer.read('trainer/trainer.yml') #调用训练结果
  4. cap = cv2.VideoCapture(0) #开启摄像头
  5. def facecapture():
  6. while True:
  7. ret, frame = cap.read() #获得每帧画面存进frame
  8. faces = face_cascade.detectMultiScale(frame, 1.3, 5)
  9. img = frame
  10. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #图片灰化
  11. for (x, y, w, h) in faces:
  12. # 画出人脸框
  13. img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
  14. id, confidence = recognizer.predict(gray[y:y + h, x:x + h])
  15. s = str(id) + str(',') + str(confidence)
  16. if confidence < 80:
  17. cv2.putText(img, str(s), (x, y - 7), 3, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
  18. # 实时展示效果画面
  19. cv2.imshow('frame2', img)
  20. k = cv2.waitKey(1) & 0xFF
  21. if k == ord('c'):
  22. t = datetime.datetime.now().date().isoformat()#获取当时时间
  23. cv2.imwrite('./save/' + str(t) + str(' ') + str(id) + '.jpg', img)#储存图片及识别信息。id为识别结果,与训练时图片命名有关
  24. print('success')
  25. if k == ord('q'):
  26. break
  27. return img

结果展示(n,1n,2n分别为不同人员,n为匹配的训练的第n张照片):

摄像头实时(很流畅~)显示样例(逗号后为置信度,越低越可靠):

 2、通信

  1. # 客户端设置
  2. s = socket.socket()
  3. host = 'ip' # ip为所用ip地址
  4. port = 12345 # 设置端口
  5. s.bind((host, port)) # 绑定端口
  6. s.listen(5)
  7. # 服务端连接
  8. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  9. address_server = ('ip', 12345)
  10. sock.connect(address_server) # 失败会自动反馈
  11. print('connected success')

利用socket进行数据传输(本文未能成功传输视频,帧率太低)

3、物体识别

直接下载训练完的结果,进行物体识别。

  1. model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
  2. model.eval()
  3. COCO_INSTANCE_CATEGORY_NAMES = [
  4. '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
  5. 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
  6. 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
  7. 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
  8. 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
  9. 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
  10. 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
  11. 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
  12. 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
  13. 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
  14. 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
  15. 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
  16. ] #官方提供的分类
  17. #识别物体
  18. def get_prediction(img_path, threshold):
  19. img = Image.open(img_path)
  20. img = img.convert('RGB')
  21. transform = T.Compose([T.ToTensor()])
  22. img = transform(img)
  23. pred = model([img])
  24. pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].numpy())]
  25. pred_boxes = [[(int(i[0]), int(i[1])), (int(i[2]), int(i[3]))] for i in list(pred[0]['boxes'].detach().numpy())]
  26. pred_score = list(pred[0]['scores'].detach().numpy())
  27. pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1]
  28. pred_boxes = pred_boxes[:pred_t + 1]
  29. pred_class = pred_class[:pred_t + 1]
  30. print("pred_class:", pred_class)
  31. print("pred_boxes:", pred_boxes)
  32. return pred_boxes, pred_class
  33. #展示识别结果
  34. def object_detection_api(img_path, threshold=0.5):
  35. boxes, pred_cls = get_prediction(img_path, threshold)
  36. img = cv2.imread(img_path)
  37. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  38. #画出物体框
  39. for i in range(len(boxes)-1):
  40. cv2.rectangle(img, (boxes[i][0]), (boxes[i][1]), color=(0, 255, 0), thickness=2)
  41. cv2.putText(img, (str(i+1)+pred_cls[i]), (boxes[i][0]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=1)
  42. plt.imshow(img)
  43. plt.show()

结果展示:

 前文包装的函数直接调用,即可获得结果:

  1. img=facecapture()
  2. # 通信,发送照片信息
  3. encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 50]
  4. img_encode = cv2.imencode('.jpg', img, encode_param)[1]
  5. data = np.array(img_encode)
  6. stringData = data.tobytes()
  7. sock.send(stringData)
  8. print(str(stringData))
  9. object_detection_api(img_path='test/0202.jpeg') # 输入物体照片路径即可
  10. cap.release()
  11. cv2.destroyAllWindows()

发送的信息(很长,不全部截取了):

 PS:物体识别可多种物体同时检测:

 以上便是所有功能及结果展示。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/765053
推荐阅读
相关标签
  

闽ICP备14008679号