1

I am trying to record the screen on my MacBook pro and store it in a video file. This isn't the end goal but this is the first step and I am noticing whatever I set my writing framerate to, I only get half of those in my final video. e.g. if I set it to 30, I'd get a video saved in 30fps but each frame would be repeated. frame 1 and 2 would be the same, frame 3 and 4 would be the same; so on and so forth. So I only get 15 frames.

I have already tried setting the framerate to 60 or 120, it gives me the same result. Whereas when I record my screen using a professional utility such as QuickTime, I get the recording as it should be, with no repeated frames and such.

import numpy as np
import cv2
from mss import mss
from PIL import Image

bbox = {'top': 270, 'left': 100, 'width': 600, 'height': 150}

sct = mss()

#fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('/Users/vipulrajan/Downloads/DinoGame/output.avi',cv2.VideoWriter_fourcc(*'XVID'), 60.0, (1200,300), isColor=0)

while 1:

    sct_img = sct.grab(bbox)
    im = np.array(sct_img)[:,:,2] #converting the image to grayscale

    out.write(im)

I have also tried adding and removing the cv2.waitKey function to the code and doesn't make any difference. Does anyone know what might be causing this behavior?

Tiger-222
  • 6,677
  • 3
  • 47
  • 60
Vipul Rajan
  • 494
  • 1
  • 5
  • 16

1 Answers1

0

Hm it seems that this code works as expected. Perhaps could you try it and post the video to help us understand what you see?

import time

import cv2
import numpy as np
from PIL import Image
from mss import mss

frame_rate = 30
width, height = 600, 150
out = cv2.VideoWriter('output.avi',
                      cv2.VideoWriter_fourcc(*'XVID'),
                      frame_rate,
                      (width, height),
                      isColor=0)
bbox = {'top': 270, 'left': 100, 'width': width, 'height': height}

with mss() as sct:
    start = time.monotonic()
    while 'capturing':
        im = np.array(sct.grab(bbox))[:,:,2]  # Convert to grayscale
        out.write(im)
        time.sleep(1 / frame_rate)

        if time.monotonic() - start > 3:  # 3 seconds
            break

out.release()
Tiger-222
  • 6,677
  • 3
  • 47
  • 60