LoginSignup
0
3

webカメラ映像からピント合った画像を保存(opencv)

Last updated at Posted at 2023-05-23

今後もたまに使いそうなのでコードを残しておく。

Python+OpenCVでwebカメラ映像を取得して好きなタイミングで画像を保存する。
実行後、キーボードの'S'で画像を保存、'Q'でプログラムの終了。
エッジ検出で使われるラプラシアンフィルタを用いてピントが悪い時には画像が保存されないようにする。

Python
import cv2

# ピント測定関数
def adjust_focus(frame):
    # ラプラシアンフィルタ(エッジ検出)に基づくピントの測定
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    focus_measure = cv2.Laplacian(gray, cv2.CV_64F).var()

    # ある値より大きければTrueを返す(値は適宜調整)
    return focus_measure > 100

# カメラ起動(カメラが複数台存在する場合はカッコ内を1とかにする)
video_capture = cv2.VideoCapture(0)

# 保存画像の名前付けのための番号
image_number = 0

while True:
    # フレームを1枚ずつ読み込む
    ret, frame = video_capture.read()

    # 上手くフレームが読み込めなければ終了
    if not ret:
        break

    # 映像を表示する
    cv2.imshow("Webcam", frame)

    # キー入力を待つ
    key = cv2.waitKey(1) & 0xFF

    if key == ord('s'):
        # 's'キーが押されたら画像を保存
        if adjust_focus(frame):
            # ピントが合っている場合のみ画像を保存
            image_number += 1
            cv2.imwrite(f"image_{image_number}.png", frame)
            print(f"Image saved: image_{image_number}.png")

    elif key == ord('q'):
        # 'q'キーが押されたら終了
        break

# デバイス、ウィンドウ閉じる
video_capture.release()
cv2.destroyAllWindows()

やっすいwebカメラで画像取得してましたがぼけまくりで、ピント自動調節してくれるwebカメラが欲しいと思いました。

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