Python AI 画像

OpenCV、matplotlib、NumPyで顔にモザイクをかける。

OpenCV、matplotlib、numpyでほとんどの画像処理ができます。 OpenCVは、インテルが開発・公開したオープンソースライブラリで現在はITseezが保守しています。 matplotlibは、Python及びその科学計算用ライブラリNumPyのためのグラフ描画ライブラリです。 conda install -c conda-forge opencvconda install numpy、でインストールできます。 matplotlibは、anacondaでpythonをインストールすると自動的にインストールされるようです。

In [1]:
# 顔モザイク

import numpy as np
import cv2
import matplotlib.pyplot as plt

顔のカスケード分類器を用います。これはインテルのVadim Pisarevsky 氏が作成したもののようです

In [2]:
#  Stump-based 24x24 discrete(?) adaboost frontal face detector.
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 
#eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # Stump-based 20x20 frontal eye detector.

モザイクをかける画像を読み込みます。画像の世界で有名なレナさんの画像を読み込みます。

In [3]:
img = cv2.imread('lenna.jpg') # bgr
# rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
In [4]:
faces = face_cascade.detectMultiScale(gray, 1.3, 5) # face detect

#img = rgb

#ratio = 0.01 # mosaic ratio 2 x 2 block
#ratio = 0.02 # mosaic ratio  4 x 4 block
#ratio = 0.03 # mosaic ratio  6 x 6 block
#ratio = 0.04 # mosaic ratio  8 x 8 block
#ratio = 0.05 # mosaic ratio  10 x 10 block
ratio = 0.06 # mosaic ratio  12 x 12 block

for (x, y, w, h) in faces:
#    img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 3) # blue rectangle
    small = cv2.resize(img[y: y + h, x: x + w], dsize=None, fx=ratio, fy=ratio, interpolation=cv2.INTER_NEAREST)
    img[y: y + h, x: x +w] = cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST)
    #ROI Region of Interest 対象領域
#    roi_gray = gray[y:y+h, x:x+w]
#    roi_color = img[y:y+h, x:x+w]
    
#    eyes = eye_cascade.detectMultiScale(roi_gray) # eye detect
    
#    for (ex, ey, ew, eh) in eyes:
#        cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2) # green

モザイク画像をファイル出力します。また、画像はbgrなのでrgbに変換して表示します。

In [5]:
cv2.imwrite('lenna_mosaic.jpg', img) # write image

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # bgr to rgb for display
plt.imshow(img) #show display
plt.title('Face mosaic'), plt.xticks([]), plt.yticks([])
plt.show()
In [ ]: