import cv2
import matplotlib.pyplot as plt
#读取照片的人脸检测:
img = cv2.imread('data/face.jpg',1)#读取一张图片
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#将图片转化成灰度
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
face_cascade.load('E:/application1/anaconda/Lib/site-packages/cv2/data/haarcascade_frontalface_alt2.xml')#一定要告诉编译器文件所在的具体位置
#此文件是opencv的haar人脸特征分类器
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow('img',img)
cv2.waitKey()
#调用人脸++进行人脸识别
import requests
from json import JSONDecoder
http_url = "https://api-cn.faceplusplus.com/facepp/v3/detect"
key = "申请的key"
secret = "申请的secret"
filepath = "data/face.jpg"
img = cv2.imread('data/face.jpg',1)#读取一张图片
data = {"api_key": key, "api_secret": secret, "return_landmark": "1"}
files = {"image_file": open(filepath, "rb")}
response = requests.post(http_url, data=data, files=files)
req_con = response.content.decode('utf-8')
req_dict = JSONDecoder().decode(req_con)
faces = req_dict['faces']
print('Number of faces detected:', len(faces))
faceNum = len(faces)
print("识别到了%d个人脸" % (faceNum))
for i in range(faceNum):
face_rectangle = faces[i]['face_rectangle']
width = face_rectangle['width']
top = face_rectangle['top']
left = face_rectangle['left']
height = face_rectangle['height']
start = (left, top)
end = (left + width, top + height)
color = (55, 255, 155)
thickness = 3
cv2.rectangle(img, start, end, color, thickness)
# 将BGR图像转变为RGB图像以打印
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 展示含有识别框的图像
plt.imshow(cv_rgb)
plt.show()
#https://blog.csdn.net/qq_37588821/article/details/80633563