Skip to content

Instantly share code, notes, and snippets.

@nikhilkumarsingh
Last active May 22, 2022 07:53
Show Gist options
  • Save nikhilkumarsingh/61601e28d097ee2e4cb9542f01b901b1 to your computer and use it in GitHub Desktop.
Save nikhilkumarsingh/61601e28d097ee2e4cb9542f01b901b1 to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
# for windows, mac users
# from PIL import ImageGrab
# for linux users
import pyscreenshot as ImageGrab
# four character code object for video writer
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# video writer object
out = cv2.VideoWriter("output.avi", fourcc, 5.0, (1366, 768))
while True:
# capture computer screen
img = ImageGrab.grab()
# convert image to numpy array
img_np = np.array(img)
# convert color space from BGR to RGB
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
# show image on OpenCV frame
cv2.imshow("Screen", frame)
# write frame to video writer
out.write(frame)
if cv2.waitKey(1) == 27:
break
out.release()
cv2.destroyAllWindows()
@ashwaqar
Copy link

Hi,
The output.avi that is generated is only 6kb and no video is getting saved. (Python 3 and Intellij)

@Casantana
Copy link

hi,
i am trying to use this code in window, but how can i resize the screenshot window?

@mailtodanish
Copy link

mailtodanish commented Mar 30, 2019

Now it will work.

import numpy as np
import cv2
from PIL import ImageGrab

fourcc = cv2.VideoWriter_fourcc('X','V','I','D') #you can use other codecs as well.
out = cv2.VideoWriter('output.avi', fourcc, 8, (500,490))
while(True):
img = ImageGrab.grab()
img_np = np.array(img)
#frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
out.write(img_np)
cv2.imshow("frame", img_np)
key = cv2.waitKey(1)
if key == 27:
break

vid.release()
cv2.destroyAllWindows()

@MysteriousSonOfGod
Copy link

can we thread it, stream live ? please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment