(一)代码如下:
import cv2
import os
import matplotlib.pyplot as plt
os.chdir("/Users/arco/Desktop/周五python/9.17")
def detect(filename):
face_cascade=cv2.CascadeClassifier("/opt/anaconda3/lib/python3.8/site-packages/cv2/data/haarcascade_frontalface_default.xml")
img=cv2.imread(filename)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
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),10)
plt.imshow(img)
plt.axis("off")
plt.show()
detect("/Users/arco/Desktop/周五python/9.17/IMG_7754.JPG")
报错过程:
(1)os.chdir()
更改目标位置
(2)def xxx:
定义
注意“:”
(3)注意缩紧
(二)识别人脸数
import face_recognition
import cv2
import matplotlib.pyplot as plt
image = face_recognition.load_image_file("/Users/arco/Desktop/周五python/9.17/IMG_7754.JPG")
face_locations=face_recognition.face_locations(image)
face_num2=len(face_locations)
print(face_num2) # The number of faces
org = cv2.imread("/Users/arco/Desktop/周五python/9.17/IMG_7754.JPG")
for i in range(0,face_num2):
top = face_locations[i][0]
right = face_locations[i][1]
bottom = face_locations[i][2]
left = face_locations[i][3]
start = (left, top)
end = (right, bottom)
color = (255,0,255)
thickness = 10
img=cv2.rectangle(org, start, end, color, thickness)
plt.imshow(img)
plt.axis('off') #去掉坐标轴
plt.show()
(三)描绘人脸轮廓
import cv2
import dlib
import matplotlib.pyplot as plt
path = "/Users/arco/Desktop/周五python/9.17/IMG_7754.JPG"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#人脸分类器
detector = dlib.get_frontal_face_detector()
# 获取人脸检测器
#predictor = dlib.shape_predictor(r"C:\Python36\Lib\site-packages\face_recognition_models\models\shape_predictor_68_face_landmarks.dat")
predictor = dlib.shape_predictor(r"/opt/anaconda3/lib/python3.8/site-packages/face_recognition_models/models/shape_predictor_68_face_landmarks.dat")
dets = detector(gray, 1)
for face in dets:
shape = predictor(img, face) # 寻找人脸的68个标定点
# 遍历所有点,打印出其坐标,并圈出来
for pt in shape.parts():
pt_pos = (pt.x, pt.y)
img=cv2.circle(img, pt_pos, 2, (0, 255, 0), 10)
plt.imshow(img)
plt.axis('off') #去掉坐标轴
plt.show()