0
0

【python入門】OpenCVを使うその2 画像にモザイクをかける

Last updated at Posted at 2023-12-21

この記事は、【完走したい】楽しくいろいろやる Advent Calendar 2023の14日目です。

画像処理がしたい

pythonに画像が入れられることは確認できたので、画像の中の顔を認識できるかやってみます。
画像処理もします。

画像から顔と目を検出する

ぬいぐるみの顔は検知できませんでした。なので、余っていた証明写真を使いました。

ここのサイトを参考に、

import cv2
import numpy as np
import matplotlib.pyplot as plt
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
faces = face_cascade.detectMultiScale(original_image, 1.1, )
for (x,y,w,h) in faces:
    original_image = cv2.rectangle(original_image,(x,y),(x+w,y+h),(1,1,1),2)
    roi_color = original_image[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_color)
 
for (ex,ey,ew,eh) in eyes:
    cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(255,255,255),1)
converted_image= cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB) 
fig = plt.figure()
plt.imshow(converted_image)

こんな感じで書いたら、ちゃんと顔と目を認識してくれました。

本題

顔と目を認識できたので、モザイクをかけていきます。

モザイクの仕方が乗ってたので参考しました。
最終的に、

import cv2
import matplotlib.pyplot as plt
src = cv2.imread('pic2023.jpg')
def mosaic(src, ratio=0.1):
    small = cv2.resize(src, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_NEAREST)
    return cv2.resize(small, src.shape[:2][::-1], interpolation=cv2.INTER_NEAREST)
def mosaic_area(src, x, y, width, height, ratio=0.1):
    dst = src.copy()
    dst[y:y + height, x:x + width] = mosaic(dst[y:y + height, x:x + width], ratio)
    return dst
face_cascade_path = 'haarcascade_frontalface_alt.xml'
face_cascade = cv2.CascadeClassifier(face_cascade_path)

src_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(src_gray)

for x, y, w, h in faces:
    dst_face = mosaic_area(src, x, y, w, h)
converted_image = cv2.cvtColor(dst_face, cv2.COLOR_BGR2RGB) 
fig = plt.figure()
plt.imshow(converted_image)

こうなりました
眼にモザイクを書けようとしたけど、まだ勉強が足りませんでした。

まとめ

参考
https://www.codexa.net/opencv_python_introduction/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0