可以发一下把这段代码加进去的完整代码不import datetimefilename = '视频_{}.avi'.format(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))video = cv2.VideoWriter(filename, fourcc, 28, (a, b))
时间: 2024-02-17 18:02:41 浏览: 70
完整代码如下:
```python
from PIL import ImageGrab
import numpy as np
import cv2
from pynput import keyboard
import threading
import datetime
flag = False
def video_record():
p = ImageGrab.grab()
a, b = p.size
fourcc = cv2.VideoWriter_fourcc(*'XVID')
filename = '视频_{}.avi'.format(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
video = cv2.VideoWriter(filename, fourcc, 28, (a, b))
while True:
im = ImageGrab.grab()
inn = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
video.write(inn)
if flag:
print('录制结束!')
break
video.release()
def on_press(key):
global flag
if key == keyboard.Key.esc:
flag = True
return False
if __name__ == '__main__':
print('开始录制!')
th = threading.Thread(target=video_record)
th.start()
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
```
在原有代码的基础上,我们添加了以下几行代码:
```python
import datetime
flag = False
def video_record():
p = ImageGrab.grab()
a, b = p.size
fourcc = cv2.VideoWriter_fourcc(*'XVID')
filename = '视频_{}.avi'.format(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
video = cv2.VideoWriter(filename, fourcc, 28, (a, b))
while True:
im = ImageGrab.grab()
inn = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
video.write(inn)
if flag:
print('录制结束!')
break
video.release()
```
其中,我们导入了datetime模块,用于获取当前的日期和时间,然后将其添加到视频文件名中。在video_record函数中,我们使用strftime方法将当前的日期和时间转换为字符串,然后将其添加到视频文件名中。因此,每次录制的视频文件名都将不同,不会覆盖之前的视频文件。
阅读全文