使用mss将使用mss的屏幕捕获部分保存到在python中使用opencv2的视频中

时间:2019-03-17 16:20:15

标签: python opencv

我想将部分屏幕保存为视频。在下面运行代码时,我可以看到窗口和fps计数(大约100-140 fps)。

代码(必须安装mssopencv2):

import numpy as np
import cv2
import time
import mss

frame_width = 1280
frame_height = 720
frame_rate = 20.0
PATH_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 up
out.release()
cv2.destroyAllWindows()

此代码未产生任何错误,因此我不明白这里出了什么问题。输出文件output.avi创建得很好,但是大小为5.7 KB(并且我没有打开该文件)。我尝试更改VideoWriter,将outfourcc移到while内-但是没有成功。还尝试更改frame_rate并将帧widthheight设置为更小的值。还查看了this问题,但不能成功。

1 个答案:

答案 0 :(得分:0)

#models.py class DefinedInfo(models.Model): user = models.CharField(max_length=30) bound = models.CharField(max_length=3) #takes 'min' or 'max' density = models.FloatField(default=0) weight =models.FloatField(default=0) .... #views.py class InfoCreateView(LoginRequiredMixin, CreateView): model = DefinedInfo template_name = 'item_new.html' fields = ['density', 'weight' ...] def form_valid(self, form): form.instance.user = self.request.user form.instance.bound = 'min' return super().form_valid(form) class InfoUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = DefinedInfo fields = ['density', 'weight' ...] template_name = 'item_edit.html' login_url = 'login' def test_func(self): obj = self.get_object() return obj.user == self.request.user #Html template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div> <h5>Define new item</h5> <div> <form action="" method="post">{% csrf_token %} {{ form|crispy }} <button" type="submit">Save </button> <button type="reset" onclick="location.href={% url 'profile' %}" >Cancel</button> </form> </div> </div> {% endblock %} 帮助之后添加了这两行:

frame = img

也许frame = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 无法将图像另存为opencv,所以这里需要另外使用np.array