Today, I want to share how to create a mosaic effect on human faces in Python. If you enjoy taking pictures, you probably also want to know how to modify them to make them look even better. This will enhance your photographic experience!
So, let's get started!
Required Documents
Face detection tool
https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_alt.xml
import libraries
・cv2
・matplotlib
・mosaic_creator.py(this is one you make by your self)
Detailed Method
mosaic_creator.py
①Calculate mosaic width and height based on the dataset.
②Apply the mosaic effect to a specified area of the original image.
③Combine the modified area with the original image.
mosaic_creator.py------------------------------------------------------
import cv2
def mosaic(img, rect, size):
①Calculate mosaic width and height based on the dataset.
(x1, y1, x2, y2) = rect
w = x2 - x1
h = y2 - y1
i_rect = img[y1:y2, x1:x2]
②Apply the mosaic effect to a specified area of the original image.
i_small = cv2.resize(i_rect, (size, size))
i_mos = cv2.resize(i_small, (w, h), interpolation=cv2.INTER_AREA)
③Combine the modified area with the original image.
img_m = img.copy()
img_m[y1:y2, x1:x2] = i_mos
return img_m
test.py
①Create a face detection model.
②Read an image file and convert it to grayscale.
③Call the mosaic function.
④Save the mosaic image.
test.py----------------------------------------------------------------
import matplotlib.pyplot as plt
import cv2
from mosaic import mosaic as mosaic
①Create a face detection model.
cascade_file = 'haarcascade_frontalface_alt.xml'
cascade = cv2.CascadeClassifier(cascade_file)
②Read an image file and convert it to grayscale.
img = cv2.imread('face.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces_list = cascade.detectMultiScale(img_gray, minSize=(900, 900))
if len(faces_list) == 0: quit()
③Call the mosaic function.
for (x, y, w, h) in faces_list:
img = mosaic(img, (x, y, x+w, y+h), 10)
④Save the mosaic image.
cv2.imwrite('face-m.png', img)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
Top comments (0)