LoginSignup
0
1

More than 1 year has passed since last update.

Google ColaboratoryでopenCV顔検出によるフェイスルビ(ファイル参照とURLローダー両方に対応)

Last updated at Posted at 2022-01-09

人物の顔の検出順にインクリメントします。

動作

GIF動画

2022_01_09_48ee0f7b-2df7-4fa4-a5f5-02aff42b1d5c.gif

Bgore:

index33.jpeg

After:

index44.jpeg

ファイル参照は複数アップロードできますが、最初の一枚が対象です。

URLローダーは 429 Too Many Requests が出ることがあります。

jpg、png対応。
機能はインクリメントのみです。
cascadeは正面顔のみです。

ノートブック

フェイスルビ

使い方

メニューバーから、

ランタイム > すべてのセルを実行

画像URLから読み込みたい場合は、事前に2枚目のコードセルの TARGET に画像のURLを入れます。

TARGET が空の場合は ファイル参照が起動します。

そもそもGoogle Colaboratoryの使い方は、という方はこちら。

ソース

コードセル1
#初期化
!rm -i -rf download
!mkdir download
!cd /content/download &&\
 wget https://github.com/opencv/opencv/archive/4.5.4.zip &&\
 unzip 4.5.4.zip
!cp -R /content/download/opencv-4.5.4/data/haarcascades /content
コードセル2
#@title 画像URLから読み込む。
TARGET = "" #@param {type:"string"}

from io import BytesIO
import requests
import time
import mimetypes
import IPython
import cv2
from PIL import Image
from operator import itemgetter

# func
def get_face_list(image=None,min_size=(30,30)):
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cascade_file = "/content/haarcascades/haarcascade_frontalface_alt2.xml"
    cascade = cv2.CascadeClassifier(cascade_file)
    face_list = list(cascade.detectMultiScale(image_gray, minSize=min_size))
    face_list.sort(key=itemgetter(0))
    return face_list

def assign_a_number(image,output_path):
    face_list=get_face_list(image)
    font = cv2.FONT_HERSHEY_PLAIN
    if len(face_list):
        i=0
        for (x,y,w,h) in face_list:
            i+=1
            fontsize=int((w/10)/1.5)
            fontweight=int(w/10)
            x=x+w if x-w<0 else x-int(w/3)
            y=y+h*2 if y-h<0 else y-int(h/3)
            cv2.putText(image, f"{i}", (x,y), font, 1 if fontsize==0 else fontsize, (0, 0, 255), 1 if fontweight<1 else fontweight)
        cv2.imwrite(output_path,image)
    else:
        print("not detected")

def tmp_display(img_path):
    fo=IPython.display.Image(img_path)
    if fo.format=="jpeg":
        IPython.display.display_jpeg(fo)
    elif fo.format=="png":
        IPython.display.display_png(fo)

# uploader
from google.colab import files

if not TARGET:
    TARGET=[]
    uploaded = files.upload()
    for fn in uploaded.keys():
        TARGET.append(f"/content/{fn}")
else:
    img=Image.open(BytesIO(requests.get(TARGET,timeout=15).content))
    out_ex=mimetypes.guess_extension(f"image/{img.format}")
    fn=f"{int(time.time())}{out_ex}"
    img.save(f"/content/{fn}",img.format)
    TARGET=[f"/content/{fn}"]

#
img_path=TARGET[0]

print("Before: ")
tmp_display(img_path)
print("")
assign_a_number(cv2.imread(img_path),img_path)
print("After: ")
tmp_display(img_path)

TARGET=""
!rm -f *.jpg *.png

参考

フリー画像

0
1
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
1