我想将屏幕的一部分保存为视频。运行下面的代码时,我可以看到窗口和 fps 计数(大约 100-140 fps)。代码(需要安装mss和opencv2):import numpy as npimport cv2import timeimport mssframe_width = 1280frame_height = 720frame_rate = 20.0PATH_TO_MIDDLE = "output.avi"fourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter(PATH_TO_MIDDLE, fourcc, frame_rate, (frame_width, frame_height))with mss.mss() as sct: # Part of the screen to capture monitor = {"top": 120, "left": 280, "width": 1368, "height": 770} while "Screen capturing": last_time = time.time() # Get raw pixels from the screen, save it to a Numpy array img = np.array(sct.grab(monitor)) img = cv2.resize(img, (1280, 720)) frame = img cv2.putText(frame, "FPS: %f" % (1.0 / (time.time() - last_time)), (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) out.write(frame) cv2.imshow('frame', frame) # Press "q" to quit if cv2.waitKey(25) & 0xFF == ord("q"): break# Clean upout.release()cv2.destroyAllWindows()这段代码没有产生任何错误,所以我不明白这里有什么问题。输出文件output.avi创建得很好,但大小为 5,7 KB(我没有打开这个文件)。我尝试改变VideoWriter,移动out和fourcc内部while- 但没有成功。还尝试更改frame_rate和设置框架width以及height更小的值。也看了这个问题,但是不能成功。
1 回答

LEATH
TA贡献1936条经验 获得超6个赞
在frame = img帮助之后添加了这两行:
frame = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
也许opencv无法保存图像,np.array因此这里需要额外使用cv2.cvtColor.
添加回答
举报
0/150
提交
取消