Help us understand the problem. What is going on with this article?

Colaboratory上でOpenCVを使って顔認識をしてみる

More than 1 year has passed since last update.

下準備

OpenCV公式GitHubで配布されているカスケード分類器のファイル(haarcascade_frontalface_default.xml)をDLしておき、Colaboratoryにアップロードする。

from google.colab import files #
f = files.upload() #ファイルアップロード

コード

import io
import numpy as np
import requests
import cv2
from matplotlib import pyplot as plt

# Web上の適当な画像を読み込む
res = requests.get('https://www.warnerbros.com/sites/default/files/styles/key_art_270x400/public/matrix_keyart.jpg')

bin_data = io.BytesIO(res.content)
file_bytes = np.asarray(bytearray(bin_data.read()), dtype=np.uint8)

img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)

# OpenCV上はBGRフォーマットだが、matplotで表示するためにRGBフォーマットに変換する
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# 事前にアップロードした分類器ファイルを使用する
cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')

# 分類器で検出
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(30, 30))

# 検出した領域を矩形で囲む
for (x, y, w, h) in face:
  cv2.rectangle(img, (x, y), (x + w, y + h), (200,0,0), 3)

# デフォルトだとグリッドとxy軸ラベルが表示されるので非表示にする
plt.grid(False)
plt.tick_params(labelbottom=False, labelleft=False, labelright=False, labeltop=False)
plt.imshow(img)

結果

opencv.png
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away