OpenCVでスカウター風フィルタを作る

2026-12-03 with Claude Code python opencv

カメラ映像にエフェクトをかけるデモに続いて、もう1つ遊べるデモを作りました。カメラの映像を緑色のガラス越しのように見せて、顔を見つけるとロックオンし、戦闘力(もちろんダミーの数字です)を測定します。たまに戦闘力が高すぎて計測不能になり、スカウターが壊れます。

戦闘力を測定し終えたところ

準備

USB接続のウェブカメラと、OpenCVの入ったPythonを用意します。Raspberry Pi OSなら次の1行です。

sudo apt install python3-opencv

顔の検出にはYuNetというモデルを使います。OpenCV Zooからface_detection_yunet_2023mar.onnxをダウンロードして、スクリプトと同じフォルダに置いてください。このモデルはOpenCV 4.8以降で読み込めます。エフェクトのデモと違って、こちらはモデルが無いと起動しません。

wget https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx

使い方

下のソースをvideo-scouter.pyという名前で保存して、実行します。

python3 video-scouter.py
  1. 顔が見つからない間は「SEARCHING...」と表示され、縦線がレーダーのように左右に動きます。
  2. カメラの前に立つと、3つの三角マーカーが回りながら顔に吸い寄せられて、ロックオンします。複数の顔が映っているときは、一番大きく映っている顔がターゲットです。
  3. ロックオンが終わると、顔の右上に戦闘力がカウントアップしながら表示されます。距離(DIST)も出ますが、顔の大きさから計算したそれっぽい数字です。
  4. 「SCAN COMPLETE」と出たら測定完了です。

rキーで再計測、qまたはESCで終了します。いったんカメラの前から離れて戻ってきても、再計測になります。

計測不能

5%の確率で、戦闘力がケタ違いの値になります。カウントアップの途中で表示が赤に変わり、数字が一気に跳ね上がった末に「ERROR」と「OVERLOAD」が出て、画面がガタガタ揺れ、ガラスにヒビが入ります。rキーで何度か再計測していると出会えるはずです。

壊れる確率はnew_target()の中の0.05で変えられます。

ソース

import cv2
import numpy as np
import random
import time
import math

# スカウター風フィルタ
# 顔を見つけるとロックオンして、戦闘力(ダミー値)を測定する
# たまに戦闘力が高すぎて、計測不能でスカウターが壊れる…
# r キーで再計測、q または ESC で終了

WINDOW = 'cv2-scouter'
GREEN = (90, 255, 120)
DARK_GREEN = (40, 140, 60)
RED = (60, 60, 255)
FONT = cv2.FONT_HERSHEY_SIMPLEX

LOCK_TIME = 0.8    # ロックオンにかかる秒数
COUNT_TIME = 1.6   # 戦闘力のカウントアップにかかる秒数

cv2.namedWindow(WINDOW)
cam = cv2.VideoCapture(0)

# 顔検出モデル(YuNet)
face_detector = cv2.FaceDetectorYN.create('face_detection_yunet_2023mar.onnx', '', (320, 240), 0.7)


def put(image, text, org, font, scale, color, thickness):
    # 文字に黒いフチを付けて、明るい背景でも読みやすくする
    cv2.putText(image, text, org, font, scale, (0, 0, 0), thickness + 3)
    cv2.putText(image, text, org, font, scale, color, thickness)


# ---------------- レンズ(緑のガラス部分) ----------------

lens = None  # (マスク画像, 輪郭の点) … 画面サイズが決まったら1回だけ作る


def make_lens(w, h):
    # 右目にかけたスカウターのガラスのような、ななめに角を落とした形
    pts = np.array([[w * 0.20, h * 0.04], [w * 0.97, h * 0.04], [w * 0.97, h * 0.96],
                    [w * 0.28, h * 0.96], [w * 0.12, h * 0.62]], np.int32)
    mask = np.zeros((h, w), np.uint8)
    cv2.fillPoly(mask, [pts], 255)
    return mask, pts


def apply_lens(image, red=False):
    # レンズの内側だけ緑色(壊れたときは赤色)のガラス越しのように見せる
    mask, pts = lens
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY).astype(np.float32)
    if red:
        tint = np.dstack([gray * 0.12, gray * 0.15, gray * 0.6 + 30])
    else:
        tint = np.dstack([gray * 0.2, gray * 0.55 + 20, gray * 0.15])
    tint = np.clip(tint, 0, 255).astype(np.uint8)
    glass = cv2.addWeighted(image, 0.2, tint, 0.8, 0)
    glass[::3] = (glass[::3] * 0.8).astype(np.uint8)  # 走査線(横じま)でモニターっぽく
    out = np.where(mask[:, :, None] > 0, glass, image)
    cv2.polylines(out, [pts], True, RED if red else GREEN, 3)
    return out


# ---------------- 計測対象(ターゲット) ----------------

def new_target():
    # 戦闘力はダミー値。たまにケタ違いの値が出て、スカウターが壊れる
    if random.random() < 0.05:  # 壊れる確率(0.05 = 5%)
        power = int(10 ** random.uniform(6, 8))
        overload = True
    else:
        power = int(10 ** random.uniform(0.7, 5))  # 5 〜 100000 くらい
        overload = False
    return {'start': time.time(), 'power': power, 'overload': overload, 'cracks': None}


def make_cracks(w, h):
    # ガラスのヒビ … ある1点から、ギザギザの線を何本も伸ばす
    cx, cy = random.randint(w // 2, w * 3 // 4), random.randint(h // 4, h * 3 // 4)
    cracks = []
    for i in range(9):
        angle = random.uniform(0, 2 * math.pi)
        x, y = cx, cy
        line = [(x, y)]
        for j in range(random.randint(4, 8)):
            angle += random.uniform(-0.5, 0.5)
            step = random.uniform(20, 60)
            x, y = int(x + math.cos(angle) * step), int(y + math.sin(angle) * step)
            line.append((x, y))
        cracks.append(np.array(line, np.int32))
    return cracks


def draw_triangle(image, cx, cy, r, angle, size, color):
    # 中心(cx, cy)から距離 r、角度 angle の位置に、中心を向いた三角形を描く
    x = cx + math.cos(angle) * r
    y = cy + math.sin(angle) * r
    tip = (x - math.cos(angle) * size, y - math.sin(angle) * size)  # 中心を向く頂点
    a1 = (x + math.cos(angle + 2.5) * size * 0.8, y + math.sin(angle + 2.5) * size * 0.8)
    a2 = (x + math.cos(angle - 2.5) * size * 0.8, y + math.sin(angle - 2.5) * size * 0.8)
    pts = np.array([tip, a1, a2], np.int32)
    cv2.fillPoly(image, [pts], color)


def draw_target(image, face, target, now):
    h, w = image.shape[:2]
    x, y, fw, fh = face[:4]
    cx, cy = int(x + fw / 2), int(y + fh / 2)
    size = max(fw, fh)
    elapsed = now - target['start']
    broken = target['overload'] and elapsed > LOCK_TIME + COUNT_TIME
    color = RED if (target['overload'] and elapsed > LOCK_TIME) else GREEN

    # --- ロックオン: 三角マーカーが回りながら顔に吸い寄せられる ---
    if elapsed < LOCK_TIME:
        p = elapsed / LOCK_TIME
        r = size * (1.8 - p)  # だんだん小さく
        spin = p * 4
        for i in range(3):
            draw_triangle(image, cx, cy, r, spin + i * 2 * math.pi / 3, 16, color)
        put(image, "LOCK ON...", (cx - 60, int(cy + r + 30)), FONT, 0.7, color, 2)
        return

    # --- ロックオン完了: 円と十字、ゆっくり回る三角マーカー ---
    r = int(size * 0.8)
    cv2.circle(image, (cx, cy), r, color, 2)
    cv2.circle(image, (cx, cy), int(r * 0.15), color, 1)
    cv2.line(image, (cx - r - 15, cy), (cx - r + 15, cy), color, 2)
    cv2.line(image, (cx + r - 15, cy), (cx + r + 15, cy), color, 2)
    cv2.line(image, (cx, cy - r - 15), (cx, cy - r + 15), color, 2)
    cv2.line(image, (cx, cy + r - 15), (cx, cy + r + 15), color, 2)
    for i in range(3):
        draw_triangle(image, cx, cy, r + 12, now * 1.5 + i * 2 * math.pi / 3, 12, color)

    # --- 戦闘力の数字: 最初はカウントアップ、途中はケタがチラチラ乱れる ---
    p = min(1.0, (elapsed - LOCK_TIME) / COUNT_TIME)
    if target['overload']:
        value = int(target['power'] * p ** 3)  # 後半で一気に跳ね上がる
    else:
        value = int(target['power'] * (1 - (1 - p) ** 3))  # 最初は速く、最後はゆっくり
    if p < 1.0:
        value += random.randint(0, max(1, value // 10))  # 数字のチラつき

    # 顔の右上に引き出し線を伸ばして、情報パネルを出す
    px, py = cx + r + 30, max(40, cy - r)
    px = min(px, w - 230)
    cv2.line(image, (int(cx + r * 0.7), int(cy - r * 0.7)), (px, py + 10), color, 1)
    cv2.line(image, (px, py + 10), (px + 210, py + 10), color, 1)
    put(image, "POWER LEVEL", (px, py), FONT, 0.6, color, 2)
    if broken and int(now * 4) % 2 == 0:
        put(image, "ERROR", (px, py + 50), FONT, 1.3, RED, 3)
    elif not broken:
        put(image, f"{value:,}", (px, py + 50), FONT, 1.3, color, 3)
    dist = 0.15 * w / max(fw, 1)  # 顔の大きさから、それっぽい距離(ダミー)を出す
    put(image, f"DIST {dist:4.1f} m", (px, py + 80), FONT, 0.55, color, 1)
    put(image, f"X{cx:04d} Y{cy:04d}", (px, py + 102), FONT, 0.55, color, 1)
    if p >= 1.0 and not target['overload']:
        put(image, "SCAN COMPLETE", (px, py + 124), FONT, 0.55, color, 1)


def draw_side_hud(image, now, color):
    # レンズの左はしに、流れていく意味ありげな文字列(ダミー)を表示
    h, w = image.shape[:2]
    x = int(w * 0.24)
    seed = int(now * 8)
    for i in range(10):
        rnd = random.Random(seed + i)  # 時間で少しずつ流れていくように
        text = ''.join(rnd.choice('0123456789ABCDEF') for k in range(6))
        put(image, text, (x, int(h * 0.12) + i * 18), cv2.FONT_HERSHEY_PLAIN, 1.0, color, 1)
    # 右下のバー表示(エネルギー残量っぽいもの)
    level = 0.5 + 0.4 * math.sin(now * 2)
    bx, by = int(w * 0.80), int(h * 0.88)
    cv2.rectangle(image, (bx, by), (bx + 100, by + 12), color, 1)
    cv2.rectangle(image, (bx, by), (bx + int(100 * level), by + 12), color, -1)


def draw_searching(image, now):
    # 顔が見つからない間は、レーダーのように縦線を左右に走らせる
    h, w = image.shape[:2]
    left, right = int(w * 0.15), int(w * 0.97)
    sx = int(left + (right - left) * (0.5 + 0.5 * math.sin(now * 2.5)))
    cv2.line(image, (sx, int(h * 0.04)), (sx, int(h * 0.96)), GREEN, 2)
    if int(now * 3) % 2 == 0:
        put(image, "SEARCHING...", (int(w * 0.45), int(h * 0.5)), FONT, 1.0, GREEN, 2)


# ---------------- メインループ ----------------

target = None
lost = 0  # 顔を見失ってからのフレーム数

while True:
    ret, image = cam.read()
    if not ret:
        break
    image = cv2.flip(image, 1)
    h, w = image.shape[:2]
    if lens is None:
        lens = make_lens(w, h)
    now = time.time()

    # 顔を探して、いちばん大きい顔をターゲットにする
    face_detector.setInputSize((w, h))
    ret, faces = face_detector.detect(image)
    face = None
    if faces is not None:
        face = max(faces, key=lambda f: f[2] * f[3])
        lost = 0
        if target is None:
            target = new_target()
    else:
        lost += 1
        if lost > 15:  # 少しの間見失っただけならターゲットを覚えておく
            target = None

    broken = (target is not None and target['overload']
              and now - target['start'] > LOCK_TIME + COUNT_TIME)

    if broken:
        # 計測不能! 画面をガタガタ揺らす
        image = np.roll(image, (random.randint(-6, 6), random.randint(-6, 6)), axis=(0, 1))

    out = apply_lens(image, red=broken)
    draw_side_hud(out, now, RED if broken else GREEN)

    if face is not None and target is not None:
        draw_target(out, face, target, now)
    elif target is None:
        draw_searching(out, now)

    if broken:
        # ガラスにヒビが入る
        if target['cracks'] is None:
            target['cracks'] = make_cracks(w, h)
        for c in target['cracks']:
            cv2.polylines(out, [c], False, (230, 230, 230), 2)
        put(out, "OVERLOAD", (int(w * 0.40), int(h * 0.90)), FONT, 1.0, RED, 3)

    put(out, "r: rescan  q/ESC: exit", (10, h - 10), FONT, 0.5, (0, 255, 255), 1)
    cv2.imshow(WINDOW, out)

    key = cv2.waitKey(10) & 0xFF
    if key in (ord('q'), 27):
        break
    if key == ord('r'):
        target = None  # 再計測

cam.release()
cv2.destroyAllWindows()