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

pygrabberを使ってOpenCVで指定したカメラの映像を取得する

Last updated at Posted at 2024-09-29

opencv-pythonでのカメラの指定

PythonでOpenCVを使ってカメラをOpenする際、ノートPCにWebカメラをつないでいる場合など、複数のカメラが認識されていると、接続のたびに認識IDがずれるため、毎回同じindexでカメラを指定できない。

cap0 = cv2.VideoCapture(0)
cap1 = cv2.VideoCapture(1)

pygrabberを使ってみる

インストールはpipで簡単に入る

pip install pygrabber

pygrabberはDirectShow経由でカメラにアクセスし、デバイス名を取得することができる。

私の環境でノートパソコンにLogicool C920ウェブカメラを接続し、デバイス名を取得してみたところ、以下のような結果になった。

PS C:\Users\xxx\dev> python
Python 3.12.5 (main, Aug 14 2024, 04:23:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from pygrabber.dshow_graph import FilterGraph
>>>
>>> graph = FilterGraph()
>>> print(graph.get_input_devices())
['FHD Camera', 'HD Pro Webcam C920']

この取得できる配列内の、目的のデバイス名のindexが、そのままOpenCVでのカメラのindexになるので、例えばC920ウェブカメラに接続したい場合は、

cap = cv2.VideoCapture(1)

で取得できる

camera_name = "HD Pro Webcam C920"

camera_opencv_index = FilterGraph().get_input_devices().index(camera_name)
cap = cv2.VideoCapture(camera_opencv_index)

のような感じにしておいてもいいかもしれない

最後に

pygrabberを使うことで指定したindexでカメラをopenすることができた。

試しに、同じwebcamを二台接続してみたところ、

PS C:\Users\xxx\dev> python
Python 3.12.5 (main, Aug 14 2024, 04:23:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from pygrabber.dshow_graph import FilterGraph
>>>
>>> graph = FilterGraph()
>>> print(graph.get_input_devices())
['FHD Camera', 'HD Pro Webcam C920', 'HD Pro Webcam C920']

となってしまった…
同じ製品を複数台使う場合は、この手法は使えないかもしれない。
(pywin32, WMIなどを使用して、カメラの詳細情報にアクセスできればもしかしたらできるかも…?)

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