蓝天资源网
当前位置:蓝天资源网 / 技术教程 / 正文

教你opencv做人识别(附源码+文档)

作者:忆笙发布时间:2021-09-08 02:03浏览数量:963次评论数量:0次

文章目录一、环境二、使用Haar级联进行人脸检测三、Haar级联结合摄像头四、使用SSD的人脸检测五、 SSD结合摄像头人脸检测六、结语一、环境1.pip install opencv-pythonpython3.9pycharm2020人狠话不多,直接上代码,注释在代码里面,不说废话。二、使用Haar级联进行人脸检测测试案例:

代码:(记得自己到下载地址下载对应的xml)

效果:

效果可以看出这个效果并不是很好。三、Haar级联结合摄像头代码:(还是用的前面得xml)

效果:

四、使用SSD的人脸检测代码:# coding=gbk"""图片人脸识别作者:川川@时间 : 2021/9/5 17:22"""import cv2import numpy as np# 下载链接:https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxtprototxt_path = r"./deploy.prototxt.txt"# 下载链接:https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20180205_fp16/res10_300x300_ssd_iter_140000_fp16.caffemodelmodel_path =r"./res10_300x300_ssd_iter_140000_fp16.caffemodel"model = cv2.dnn.readNetFromCaffe(prototxt_path, model_path)image = cv2.imread("2.jpg")h, w = image.shape[:2]blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300),(104.0, 177.0, 123.0))model.setInput(blob)output = np.squeeze(model.forward())font_scale = 1.0for i in range(0, output.shape[0]): confidence = output[i, 2] if confidence > 0.5: box = output[i, 3:7] * np.array([w, h, w, h]) start_x, start_y, end_x, end_y = box.astype(np.int) cv2.rectangle(image, (start_x, start_y), (end_x, end_y), color=(255, 0, 0), thickness=2) cv2.putText(image, f"{confidence*100:.2f}%", (start_x, start_y-5), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 0, 0), 2)cv2.imshow("image", image)cv2.waitKey(0)cv2.imwrite("beauty_detected.jpg", image)可以发现SSD效果特别好!效果:

我们可以看到现在的识别效果非常好了。五、 SSD结合摄像头人脸检测代码:# coding=gbk"""作者:川川@时间 : 2021/9/5 17:26SSD结合摄像头的人脸检测"""import cv2import numpy as npprototxt_path = "deploy.prototxt.txt"model_path = "res10_300x300_ssd_iter_140000_fp16.caffemodel"model = cv2.dnn.readNetFromCaffe(prototxt_path, model_path)cap = cv2.VideoCapture(0)while True: _, image = cap.read() h, w = image.shape[:2] blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0)) model.setInput(blob) output = np.squeeze(model.forward()) font_scale = 1.0 for i in range(0, output.shape[0]): confidence = output[i, 2] if confidence > 0.5: box = output[i, 3:7] * np.array([w, h, w, h]) start_x, start_y, end_x, end_y = box.astype(np.int) cv2.rectangle(image, (start_x, start_y), (end_x, end_y), color=(255, 0, 0), thickness=2) cv2.putText(image, f"{confidence*100:.2f}%", (start_x, start_y-5), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 0, 0), 2) cv2.imshow("image", image) if cv2.waitKey(1) == ord("q"): breakcv2.destroyAllWindows()cap.release()效果:

六、结语如果你想更深了解这些原理,去读一下opencv文档吧,中文官方文档如下:https://woshicver.com/1在很多人调用xm会遇到一些坑,我在这里说一下,读取xml的时候用相对路径./这种,参考我的,建议不要路径中出现中文。

忆笙

忆笙 主页 联系他吧

人间山河远阔,只想与你同行。

欢迎 发表评论: