gpt4 book ai didi

python - 使用OpenCV和PyAutoGUI构建的我的屏幕录像机仅记录一帧

转载 作者:行者123 更新时间:2023-12-02 16:09:07 25 4
gpt4 key购买 nike

我正在使用numpy,OpenCV和PyAutoGUI在Python中构建一个屏幕录像机。我已经将tkinter用于GUI。我的屏幕录像机的问题在于,当我单击“记录屏幕”按钮时,它只能记录一帧,然后屏幕被卡住,无法执行任何操作。到目前为止,这是我的代码:

from tkinter import *
import cv2
import numpy as np
import pyautogui

resolution = (1366,768)
指定视频编解码器:
codec = cv2.VideoWriter_fourcc(*"XVID")
指定输出文件的名称:
filename = "Recordings.avi"
指定帧速率(我们可以选择任何值并进行实验):
fps = 30.0
创建一个 VideoWriter对象:
out = cv2.VideoWriter(filename, codec, fps, resolution)

def startRecording():

window.iconify()
while True:
img = pyautogui.screenshot()

# Convert the screenshot to a numpy array
frame = np.array(img)

# Convert it from BGR(Blue, Green, Red) to
# RGB(Red, Green, Blue)

frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

# Write it to the output file
out.write(frame)

def stopRecording():
cv2.destroyAllWindows()
out.release()
window.destroy()



window = Tk()
window.title("Screen Recorder")
window.geometry("400x150")
window.config(bg='pink')

recordButton = Button(window,text="Record(F9)",font=("Bell MT",20),width=20,command=startRecording)
recordButton.pack(pady=(10,0))

stopButton = Button(window,text="Stop(F10)",font=("Bell MT",20),width=20,command=stopRecording)
stopButton.pack(pady=(10,0))

mainloop()

最佳答案

您不能在按钮回调中进行阻止调用。
如您所写,startRecording将永远不会结束,因此将阻止tkinter mainloop。录制可能有效,但是您的UI变得无响应。
最好的选择是安排录制时间(查找 after 方法):每x毫秒录制一帧。
这是一个基于原始代码的简化示例(您需要完成它)

continueRecording = True # must be declared before stopRecording 
window = Tk() # must be declared before recordOneFrame

def stopRecording():
global continueRecording
continueRecording = False

def recordOneFrame():
global continueRecording
img = pyautogui.screenshot()

# Convert the screenshot to a numpy array
frame = np.array(img)

# Convert it from BGR(Blue, Green, Red) to
# RGB(Red, Green, Blue)

frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

# Write it to the output file
out.write(frame)
if continueRecording:
window.after(round(1/25. * 1000),recordOneFrame)


def startRecording():
recordOneFrame()

关于python - 使用OpenCV和PyAutoGUI构建的我的屏幕录像机仅记录一帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64369974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com