【OpenCV】 Webカメラの画面をマウスの右クリックで回転させたい
やりたいこと
Windows10、Python3.9にて
PCにwebカメラ(1~2台)をUSB接続して、他のソフトと組み合わせて車が走っているときのデータを取りたい。他のソフトとの兼ね合いで、画像はPCの特定の位置に画面を小さくして表示。webカメラの取り付け位置が、車のいろんなところに取り付けるので、上下反転したり、90度横向きの場合もあるので、カメラの表示は右クリックしたら回転するようにしたい。カメラも1台の場合もあるので、1台でもNGにならないようにしたい。
解決したいこと
できたこと
①カメラの画像2台表示
②カメラ1台でも2台でも NGでない。
できてない事
カメラの表示画面上で右クリックしても画像が回転しない。
該当するソースコード
Windows10、Python3.9
from datetime import datetime # 時刻関係のライブラリ
import cv2 # OpenCV のインポート
import tkinter as tk
countx = 0
county = 0
#-------------------------------------
# マウスイベント時に処理を行う
def mouse_event1(event, x, y, flags, param):
global countx
if event == cv2.EVENT_RBUTTONUP:
countx = (countx + 1)% 4
#-------------------------------------
# マウスイベント時に処理を行う
def mouse_event2(event, x, y, flags, param):
global county
if event == cv2.EVENT_RBUTTONUP:
county = (countx + 1)% 4
#-------------------------------------
i = 1
flag = True
captures = []
#カメラの台数確認
while( flag ):
capture = cv2.VideoCapture(i)
ret, frame = capture.read()
flag = ret
if flag:
i += 1
captures.append( capture )
while(True):
for i, capture in enumerate( captures, start=1 ):
ret, frame = capture.read()
#画像をアスペクト比を変えずにリサイズする
def scale_to_width (frame, width):
h, w = frame.shape[:2]
height = round(h * (width / w))
dst = cv2.resize(frame, dsize=(width, height))
#print(h,w,height,width,i)
return dst
dst = scale_to_width (frame, 450)
cv2.imshow( 'frame' + str(i), dst )
cv2.moveWindow('frame1', 1005,70) # カメラ1表示位置指定
cv2.moveWindow('frame2', 1465,70) # カメラ2表示位置指定
# 右クリックでFrame1回転
if countx == 1:
frame1 = cv2.rotate(frame1,cv2.ROTATE_90_CLOCKWISE)
elif countx == 2:
frame1 = cv2.rotate(frame1,cv2.ROTATE_180)
elif countx == 3:
frame1 = cv2.rotate(frame1,cv2.ROTATE_90_COUNTERCLOCKWISE )
cv2.setMouseCallback('frame1', mouse_event1)
cv2.namedWindow('frame1', 16)
# 右クリックでFrame2回転
if county == 1:
frame2 = cv2.rotate(frame2,cv2.ROTATE_90_CLOCKWISE)
elif county == 2:
frame2 = cv2.rotate(frame2,cv2.ROTATE_180)
elif county == 3:
frame2 = cv2.rotate(frame2,cv2.ROTATE_90_COUNTERCLOCKWISE )
cv2.setMouseCallback('frame2', mouse_event2)
cv2.namedWindow('frame2', 16)
key = cv2.waitKey(1)
prop_val = cv2.getWindowProperty('frame1', cv2.WND_PROP_ASPECT_RATIO)
if (key != -1) or (prop_val < 0):
break
capture.release()
cv2.destroyAllWindows()
#ここまで
#------------------------------------
### 自分で試したこと
cap1、cap2とカメラ別に設定した場合、うまくいくようですが
カメラ1台のみの場合エラーで表示されません。
cap1 = cv2.VideoCapture(1)
cap2 = cv2.VideoCapture(2)
while True:
# VideoCaptureから1フレーム読み込む
ret, frame1 = cap1.read() # 戻り値のframeがimg
ret, frame2 = cap2.read() # 戻り値のframeがimg
以上よろしくお願いします
0 likes