Install
Environment: python3.6.5
opencv version: 3.4.1.15
Extension pack version: 3.4.1.15
It is best to open a virtual environment to install. What is a virtual environment? In a word, it is to prevent dependency conflicts in an environment. Thereby opening up another sub-environment. Create a virtual environment method: I can directly choose when I create a new project on pycharm. Other creation methods are Baidu.
If you don’t know the virtual environment yet, just move here
face recognition code
import cv2
if __name__ == '__main__':
img = cv2.imread("3.jpg")
img = cv2.resize(img, None, fy=0.5, fx=0.5)
face_data = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
faces = face_data.detectMultiScale(img)
for x, y, w, h in faces:
cv2.rectangle(img, pt1=(x, y), pt2=(x + w, y + h), color=(0, 0, 255))
cv2.imshow("co", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Renderings:
mosaic code
import cv2
import numpy as np
if __name__ == '__main__':
img = cv2.imread("3.jpg")
img = cv2.resize(img, None, fy=0.5, fx=0.5)
face_data = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
faces = face_data.detectMultiScale(img)
for x, y, w, h in faces:
mask = None
mask = img[y:y+h, x:x+w]
mask = mask[::6, ::6]
mask = np.repeat(mask, 6, axis=0)
mask = np.repeat(mask, 6, axis=1)
img[y:y+h, x:x+w] = mask[:h, :w]
cv2.imshow("co", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
renderings
Face recognition code in video
import cv2
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, img = cap.read()
face_data = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
faces = face_data.detectMultiScale(img)
for x, y, w, h in faces:
cv2.rectangle(img, pt1=(x, y), pt2=(x + w, y + h), color=(0, 0, 255))
cv2.imshow("video", img)
if cv2.waitKey(10) == ord('q'):
break
cv2.destroyAllWindows()
focus
Use the haarcascade_frontalface_alt.xml trained by others in opencv in github.
A video is equivalent to a photo
Color sorting in opencv is BGR
If you want to modify the accuracy of face recognition, you can adjust the scaleFactor default 1.1 and minNeighbors default 3 in the detectMultiScale method