0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python + OpenCVでカメラの使い方メモ

Posted at

はじめに

pythonでカメラを使いたいときのコード。これが動くことを確認してから、各種の認識コードを試す。
多くのサンプルではカメラを簡単に表示できるのに、自分の環境ではDirectShowを書かないと動かず、解決までかなり時間を取られたのでメモ。

また、カメラの露出やピントを固定する際のamcap.exeのような設定画面を表示できるので、それも追加。

解像度を指定する方法も追加。

環境

Windows 11
Logitech HD Pro Webcam C920
python 3.11.6

camera.py
import cv2 #openCV

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) #0番目のカメラ。DirectShow書かないと動かなかったwindows
cap.set(cv2.CAP_PROP_SETTINGS, 1)#カメラ設定ウィンドウ表示

cap.set(cv2.CAP_PROP_FPS, 30)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 450)

while True: #永久ループ
    ret, video = cap.read()#画像取得

    cv2.imshow('camera' , video)#表示

    key =cv2.waitKey(10) #ESCで終了
    if key == 27:
        break


cap.release() #終了
cv2.destroyAllWindows()

カメラ環境が特殊な場合

カメラが2台ついているとか、認識してくれない場合に、接続状況を確認するコード。

camList.py
import cv2

for n in range(0, 20): 
    cap = cv2.VideoCapture( n, cv2.CAP_DSHOW )
    if cap.isOpened(): 
        print("VideoCapture(", n, ") : Found")
    else:
        print("VideoCapture(", n, ") : None")
    cap.release()

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?