LoginSignup
4

More than 1 year has passed since last update.

Python3: OpenCV で顔認識

Last updated at Posted at 2017-06-19

次のページを参考にしました。

OpenCVで顔認識をしてみた

入力ファイル
family-557100_1280.jpg

出力ファイル
family_after.jpg

front_face.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
#                       May/16/2021
# ------------------------------------------------------------------
import cv2
import sys

sys.stderr.write("*** start ***\n")

image_file = sys.argv[1]
image_after = sys.argv[2]

folder="/usr/share/opencv4/haarcascades/" 
#cascade_file = folder + "haarcascade_frontalface_alt.xml"
#cascade_file = folder + "haarcascade_frontalface_alt2.xml"
#cascade_file = folder + "haarcascade_frontalface_alt_tree.xml"
cascade_file = folder + "haarcascade_frontalface_default.xml"

img = cv2.imread(image_file)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cascade = cv2.CascadeClassifier(cascade_file)
width=100
face_list = cascade.detectMultiScale(img_gray, minSize=(width, width))

if len(face_list) == 0:
    sys.stderr.write ("Fail recognise\n")
    quit()

for (x, y, w, h) in face_list:
    print("顔の座標 =", x, y, w, h)
    color = (0, 0, 225)
    pen_w = 8
    cv2.rectangle(img, (x, y), (x+w, y+h), color, thickness = pen_w)

cv2.imwrite(image_after, img)

sys.stderr.write("*** end ***\n")
# ------------------------------------------------------------------

実行方法

./front_face.py family-557100_1280.jpg family_after.jpg

次の環境で動作を確認

Arch Linux (5.4.13-arch1-1)
Python 3.8.1

Arch Linux で カスケードのファイルを探す方法

pacman -Ql opencv | grep haarcascade

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
4