4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python + OpenCVで笑顔のリアルタイム検知

Last updated at Posted at 2021-02-07

背景

オンラインハッカソンに参加した際に作成したアプリが入賞したので記念に載せておこうとおもった。
件のハッカソンでは、「難しい技術に挑戦しているか、新しい技術に挑戦しているか」が評価基準のひとつだったので、今回はOpenCVとPySimpleGUIに挑戦してみた。プログラムの全容はここ

概要

リアルタイムに笑顔を検知するアプリ、を作成しました。

・笑顔の時だけ赤い長方形が表示され、その長方形のアスペクト比を笑顔の点数にしている。
・点数に定数を乗じたものを右側にリアルタイム描画している。
・py2appでmac用のスタンドアローンアプリになっている。

コード

OpenCVとPySimpleGUIではリアルタイムに処理をしたいので、基本的に

sample.py
while True
    #何かしらの処理
  if a:  #何かしらの条件
      break

という形になる。

実際のコードを抜粋すると、

SmileDetector.py
def main():
  #省略
  while True:
    stage += 1

    event, values = win.read(timeout=1)
    if event in (None, "Quit"):
        break

    ret, frame = camera.read()

    image = frame[90:990, 0:-1]
    image_ = cv2.resize(image, (750,400), cv2.INTER_LANCZOS4)


    # -----------------  Process images here. ---------------- #
    gray = cv2.cvtColor(image_, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
    smile_value = 0

    for (x, y, w, h) in faces:
        cv2.rectangle(image_, (x, y), (x + w, y + h), (255, 0, 0), 2)
        face = image_[y:y + h, x:x + w]
        face_gray = gray[y:y + h, x:x + w]

        smiles = smile_cascade.detectMultiScale(face_gray, 1.8, 20)
        for (sx, sy, sw, sh) in smiles:
            cv2.rectangle(face, (sx, sy), ((sx + sw), (sy + sh)), (0, 0, 255), 2)
        
           #省略

    # ----------------- End of Image Processing ----------------- #  

こんな感じ。

while True で常に画面の情報を取り込みつつ、それに対して画像処理を加えていく。

OpenCV単体でリアルタイム画像処理をする場合も、PySimpleGUI単体でアプリを作る場合の両者とも、
while True: を使うので、その部分を一つにまとめることで実装できる。

終わりに

入賞できて五千円以内の技術書が貰えることになった。嬉しかった。
このアプリをオンライン面接のバックで動かしておいて、笑えてるかどうかをチェックして面接を乗り越えたい。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?