简体   繁体   中英

Save capture part of screen using mss to video using opencv2 in python

I want to save part of screen as video. When running code below I can see the window and fps count on it (around 100-140 fps).

Code (installed mss and opencv2 are required):

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()

This code not produced any errors, so I don't understand what's wrong here. Output file output.avi created fine, but with size 5,7 KB (and this file I didn't open). I tried change VideoWriter , move out and fourcc inside the while - but didn't succeed. Also tried to change frame_rate and set frame width and height to more smaller values. Also looked at this question, but cannot succeed.

Added those two lines after frame = img helps:

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

Maybe opencv can't save image as np.array so here need additional usage of cv2.cvtColor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM