2022年5月6日金曜日

PySimpleGUIとOpenCVでwebカメラ画像をblur関数でぼかして表示する

PySimpleGUIとOpenCVでwebカメラ画像をblur関数でぼかして表示するには、以下のサンプルプログラムを参照してください。
blurの引数には以下を指定します。
・元画像
・ksize : カーネルサイズ。奇数かつ正の値を指定します。

サンプルコードの実行手順

1. PySimpleGUIとOpenCVがインストールされた環境の構築
以下のページを参照して、環境を構築します。
PySimpleGUIとOpenCVをインストールしてwebカメラの映像をウインドウを表示する

2. サンプルプログラムの作成と実行
以下のファイルを保存して、実行します。ksizeはスライダーによって変更できます。
psgui_opencv_blur.py
import PySimpleGUI as sg
import cv2


sg.theme('SystemDefault')
layout = [
  [
    sg.Text("ksize"),
    sg.Slider(key='ksize', range=(1, 51), resolution=2, default_value=5, orientation='horizontal', expand_x=True)
  ],
  [sg.Image(key='img1'), sg.Image(key='img2')]
]

# webカメラをキャプチャー
capture = cv2.VideoCapture(0)

# webカメラの解像度を取得
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)/2)
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)/2)
window = sg.Window("webカメラ画面", layout=layout, finalize=True)
# イベントループ
while True:
  event, values = window.read(timeout=50)
  if event == sg.WIN_CLOSED:
    break
  rv, frame = capture.read()
  if rv is True:
    # 左右に並べるために縦横のサイズを半分にリサイズ
    resized = cv2.resize(frame, (width, height))
    # blur関数でぼかす
    ksize = int(values['ksize'])
    bi = cv2.blur(resized, ksize=(ksize, ksize))
    # pngに変換して、Image更新
    img = cv2.imencode('.png', resized)[1].tobytes()
    img2 = cv2.imencode('.png', bi)[1].tobytes()
    window['img1'].update(data=img)
    window['img2'].update(data=img2)


capture.release()
window.close()

・実行方法
以下のコマンドを実行します。
python3 psgui_opencv_blur.py

関連情報

PySimpleGUIで画像を表示する

・OpenCVに関する他の記事はこちらを参照してください。

0 件のコメント:

コメントを投稿