马赛克
face = img[162:428,297:527] # 人脸坐标区域face = face[::10,::10] # 每10个中取出一个像素,马赛克face = np.repeat(face, 10, axis=0) # 行方向重复10次face = np.repeat(face, 10, axis=1) # 列方向重复10次img[162:428,297:527] = face[:266,:230] # 填充,保持尺寸一致cv2.imshow('bao', img)cv2.waitKey(0)cv2.destroyAllWindows()
人脸识别
人脸特征参数下载地址
opencv/data/haarcascades at 4.x · opencv/opencv · GitHub
# 人脸特征详细说明,1万多行,计算机根据这些特征,进行人脸检测# 符合其中一部分说明,算作人脸# 级联分类器、检测器face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_alt.xml')faces = face_detector.detectMultiScale(img) # 坐标x,y,w,hfor x,y,w,h in faces:cv2.rectangle(img,pt1=(x,y),pt2=(x+w,y+h), color=[0,0,255],thickness=2) # 矩形cv2.imshow('face', img)cv2.waitKey(0)cv2.destroyAllWindows()
多人脸
调整参数
gray = cv2.cvtColor(img, code=cv2.COLOR_BGR2GRAY)face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_alt.xml')faces = face_detector.detectMultiScale(gray,scaleFactor=1.2, # 缩放minNeighbors=3) # 坐标x,y,w,hfor x,y,w,h in faces:cv2.rectangle(img,pt1=(x,y),pt2=(x+w,y+h), color=[0,0,255],thickness=2) # 矩形cv2.imshow('face', img)cv2.waitKey(0)cv2.destroyAllWindows()
gray = cv2.cvtColor(img, code=cv2.COLOR_BGR2GRAY)face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_alt.xml')faces = face_detector.detectMultiScale(gray,scaleFactor=1.2, # 缩放minNeighbors=3, minSize=(40,40)) # 设置检测框大小,过滤太小的框for x,y,w,h in faces:# cv2.rectangle(img,pt1=(x,y),pt2=(x+w,y+h), color=[0,0,255],thickness=2) # 矩形cv2.circle(img, center=(x+w//2, y+h//2),radius=w//2,color=[0, 255, 0]) # 圆形cv2.imshow('face', img)cv2.waitKey(0)cv2.destroyAllWindows()
人脸贴纸
gray = cv2.cvtColor(img, code=cv2.COLOR_BGR2GRAY)face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_alt.xml')faces = face_detector.detectMultiScale(gray) # 设置检测框大小,过滤太小的框star = cv2.imread('./star.png')for x,y,w,h in faces:star_s = cv2.resize(star, (w//4, h//4))w1 = w//4h1 = h//4for i in range(h1):for j in range(w1): # 遍历图片数据if not (star_s[i,j] > 200).all(): # 红色img[i+y,j+x+3*w//8] = star_s[i,j]cv2.imshow('face', img)cv2.waitKey(0)cv2.destroyAllWindows()