When I try to capture a video screenshot of my screen in a region suddenly the .avi output file becomes a 7kb. The is no error, so I do not know how to fix this The output video is fine before selecting the region. how can i fix this problem?
# create the video write object
img = pyautogui.screenshot(region=(350, 800, 500, 150)) # --->saves 7kb .avi file
img = pyautogui.screenshot() # --->works fine
this code just returns the screenshot, it does not save anything. show your full code (minimal reproducible example)
Here is the full code
import cv2
import numpy as np
import pyautogui
# display screen resolution, get it from your OS settings
import tkinter as tk
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
SCREEN_SIZE = (screen_width, screen_height)
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# create the video write object
out = cv2.VideoWriter("output.avi", fourcc, 20.0, (SCREEN_SIZE))
while True:
# make a screenshot
img = pyautogui.screenshot(region=(350, 800, 500, 150))
# convert these pixels to a proper numpy array to work with OpenCV
frame = np.array(img)
# convert colors from BGR to RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# write the frame
out.write(frame)
# show the frame
cv2.imshow("screenshot", frame)
# if the user clicks q, it exits
if cv2.waitKey(1) == ord("q"):
break
# make sure everything is closed when exited
cv2.destroyAllWindows()
out.release()
To start debug I would try and save img
separately, so that you know what you actually get on line 17.
Also note that pyautogui
just uses pyscreeze
for screenshot functions, which in turn uses Pillow.ImageGrab on Windows. By the way Pillow.ImageGrab now works also on Mac, but pyscreeze still uses subrpocess call to screencapture
The problem was this part and changing the last two parameters solved the problem.
out = cv2.VideoWriter("output.avi", fourcc, 20.0, (SCREEN_SIZE))
thanks for posting back. how did you change them in order to work?
I just changed this part :
out = cv2.VideoWriter("output.avi", fourcc, 8.0, (500, 150))
but the problem is somehow remained. Still it is inconsistent. Like three times out of five times it saves the .avi file as 6kb again, specially if I change the saving path it is going to record as 6kb constantly. It is really strange.
changing
fourcc = cv2.VideoWriter_fourcc(*"XVID") to :
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
also solved the problem with inconsistency.