前提・実現したいこと
pythonでopenCVとtkinterを用いてwebカメラの録画をしようとしています。
tkinterのCanvasにカメラの映像を流しつつ、必要な部分を録画できるように作成しています。
発生している問題・エラーメッセージ
CV2のwriteで録画はできるんですが、PILパッケージのImageTk.PhotoImageでtkinterのcanvasに貼り付けられるように変換する処理を組み込むと、録画がエラーになります。
init()を実行した後、threadingでrecord()をスタートしています。
bootKeyとrecKeyはtkinterのボタンで変わるようにしています。
python
1def init(): 2 global cap 3 global w 4 global h 5 global out 6 cap = cv2.VideoCapture(1) 7 fps = int(cap.get(cv2.CAP_PROP_FPS)) 8 w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 9 h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 10 fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') 11 out = cv2.VideoWriter('output.mp4', fourcc, fps, (w, h)) 12 13def record(): 14 global frame 15 if bootKey: 16 ret, frame = cap.read() 17 frame = cv2.resize(frame, dsize=(w, h)) 18 print(w) 19 print(h) 20 if recKey: 21 out.write(frame) 22 im = ImageTk.PhotoImage(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))) 23 print(3) 24 canvas.create_image(w, h, image=im) 25 root.after(1,record) 26 else: 27 print("exit")
試したこと
im=ImageTk~~とcanvas.create_Imageをコメントアウトすると録画できることは確認しました。
普通に考えるとImageTkとCV2.writeが干渉しているように思いますがいかがでしょうか?
###解決したコード
python
1import tkinter as tk 2import threading 3import cv2 4from PIL import Image,ImageTk 5 6bootKey=True 7recKey=False 8 9def CV_init(): 10 global cap 11 global w 12 global h 13 global out 14 cap = cv2.VideoCapture(1) 15 fps = int(cap.get(cv2.CAP_PROP_FPS)) 16 w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 17 h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 18 print(w) 19 print(h) 20 rate_wh = 240 / w # width=240 21 w = int(w * rate_wh) 22 h = int(h * rate_wh) 23 print(w) 24 print(h) 25 fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') 26 out = cv2.VideoWriter('output.mp4', fourcc, fps, (w, h)) 27 print("cv_init_fin") 28 29def CV_loop(): 30 global frame 31 global im 32 if bootKey: 33 ret, frame = cap.read() 34 frame = cv2.resize(frame, dsize=(w, h)) 35 if recKey: 36 out.write(frame) 37 im = ImageTk.PhotoImage(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))) 38 canvas.create_image(0, 0, image=im) 39 root.after(1,CV_loop) 40 else: 41 print("exit") 42 CV_exit() 43 44def CV_exit(): 45 cap.release() 46 out.release() 47 root.quit() 48 49def recording(): 50 global recKey 51 if recKey: 52 recKey=False 53 else: 54 recKey=True 55 56def finish(): 57 global bootKey 58 global recKey 59 bootKey=False 60 recKey=False 61 62root=tk.Tk() 63canvas=tk.Canvas(root) 64canvas.pack() 65btn_rec=tk.Button(root,text="rec",command=recording) 66btn_rec.pack() 67btn_fin=tk.Button(root,text="fin",command=finish) 68btn_fin.pack() 69CV_init() 70threading.Thread(target=CV_loop).start() 71root.mainloop()
回答1件
あなたの回答
tips
プレビュー