Daily Archives: June 28, 2020

CV(3) Eye Mosaic

Published by:

検出領域にモザイク処理

検出した領域にモザイクをかけたりすることもできる。

Viでサンプルコードを作成

$ vi test3.py 

import cv2
  
face_cascade_path = '/usr/local/opt/opencv/share/'
                    'OpenCV/haarcascades/haarcascade_frontalface_default.xml'
eye_cascade_path = '/usr/local/opt/opencv/share/'
                   'OpenCV/haarcascades/haarcascade_eye.xml'

face_cascade = cv2.CascadeClassifier(face_cascade_path)
eye_cascade = cv2.CascadeClassifier(eye_cascade_path)

src = cv2.imread('data/src/lena_square.png')
src_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(src_gray)

ratio = 0.05

for x, y, w, h in faces:
    cv2.rectangle(src, (x, y), (x + w, y + h), (255, 0, 0), 2)
    face = src[y: y + h, x: x + w]
    face_gray = src_gray[y: y + h, x: x + w]
    eyes = eye_cascade.detectMultiScale(face_gray)
    for (ex, ey, ew, eh) in eyes:
        # cv2.rectangle(face, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
        eye = face[ey: ey + eh, ex: ex + ew]
        small = cv2.resize(eye, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_NEAREST)
        face[ey: ey + eh, ex: ex + ew] = cv2.resize(small, (ew, eh), interpolation=cv2.INTER_NEAREST)

cv2.imwrite('data/dst/opencv_eye_detect_mosaic.jpg', src)

処理結果

$ python2 test3.py
[ INFO:0] Initialize OpenCL runtime…

$ ls -al data/dst/
total 512
drwxr-xr-x 4 chen staff 128 6 25 01:45 .
drwxr-xr-x 5 chen staff 160 6 20 00:50 ..
-rw-r–r–@ 1 chen staff 108333 6 25 01:51 opencv_eye_detect_mosaic.jpg
-rw-r–r–@ 1 chen staff 110477 6 25 01:07 opencv_face_detect_rectangle.jpg

ファイル data/dst/opencv_eye_detect_mosaic.jpg が作成されたことが確認した。