python opencv capture screen code example
Example 1: python cv2 screen capture
import numpy as np
import cv2
from PIL import ImageGrab
while True:
img = ImageGrab.grab(bbox=(0, 1000, 100, 1100))
img_np = np.array(img)
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0Xff == ord('q'):
break
cv2.destroyAllWindows()
Example 2: python opencv camera capture
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Example 3: take screenshot of video python
import cv2
import os
import time
def get_frames(inputFile,outputFolder,step,count):
'''
Input:
inputFile - name of the input file with directoy
outputFolder - name and path of the folder to save the results
step - time lapse between each step (in seconds)
count - number of screenshots
Output:
'count' number of screenshots that are 'step' seconds apart created from video 'inputFile' and stored in folder 'outputFolder'
Function Call:
get_frames("test.mp4", 'data', 10, 10)
'''
step = step
frames_count = count
currentframe = 0
frames_captured = 0
try:
if not os.path.exists(outputFolder):
os.makedirs(outputFolder)
except OSError:
print ('Error! Could not create a directory')
cam = cv2.VideoCapture(inputFile)
frame_per_second = cam.get(cv2.CAP_PROP_FPS)
while (True):
ret, frame = cam.read()
if ret:
if currentframe > (step*frame_per_second):
currentframe = 0
name = './data/frame' + str(frames_captured) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
frames_captured+=1
if frames_captured > frames_count-1:
ret = False
currentframe += 1
if ret == False:
break
cam.release()
cv2.destroyAllWindows()