LoginSignup
0
1

More than 3 years have passed since last update.

cv2.VideoCaptureで設定可能なカメラパラメーターの一覧を取得して辞書型にする

Posted at

困っていたこと:cv2.VideoCapture()を利用するとき、カメラ出力設定を手動で入力しなければならない。

WIDTH = 100
HEIGHT = 100
FPS = 10
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)
cap.set(cv2.CAP_PROP_FPS, FPS)
ret, frame = cap.read() #うまくいったりいかなかったり

出力設定によっては最も値の近い解像度やFPSに自動設定されたり、またはcap.read()でエラーを吐いたりと様々。opencvからはusbカメラの対応する設定情報にアクセスできなかったので、v412-ctlコマンドから取得する。

一覧を出力するコマンド
import subprocess
import re
cmd = 'v4l2-ctl --device /dev/video0 --list-formats-ext'
proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
outs_bytes = proc.communicate()[0]
outs_str = outs_bytes.decode('utf-8')
outs_str_lists = outs_str.split('\n')

d = {}
i = 0
for line in outs_str_lists:
    if "Pixel Format" in line:
        pixelformat = line.split(":")[-1].strip()
    if "Size:" in line:
        resolution = line.split()[-1]
    if "Interval" in line:
        fps = re.findall("(?<=\().+?(?=\))",line)[0].split()[0]
        _d = {"format":pixelformat,"height":resolution.split("x")[1],"width":resolution.split("x")[0],"fps":fps}
        d[i] = _d
        i +=1
print d
結果
{0: {'format': "'MJPG' (compressed)",
  'height': '2880',
  'width': '3840',
  'fps': '15.000'},
 1: {'format': "'MJPG' (compressed)",
  'height': '2880',
  'width': '3840',
  'fps': '10.000'},
 2: {'format': "'MJPG' (compressed)",
  'height': '2880',
  'width': '3840',
  'fps': '5.000'},

これで辞書型として対応する設定を取得することができたので、プログラム内部にカメラ情報を変数として利用することが可能になった。

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