Laggy Webcam Feed

Hello,
I am trying to set up a simple code on my Windows laptop(Lenovo Legion5) to capture and write images in a select region of interest.
Before actually capturing it, I wanted to do a test run on the webcam to see how it’s working, but for some reason the feed is extremely laggy for some reason.
Here is the code from the cells I’ve been running:

#import os
import cv2
#import time
#import uuid

t,b,r,l = 250,470,450, 150
while True:
cam = cv2.VideoCapture(0)
(ret,frame) = cam.read()
cv2.rectangle(frame, (l,t), (r,b),(0,255,0),1)
#cv2.imshow(‘frame’,frame)
roi = frame[t:b,l:r]

cv2.imshow('roi', roi)

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

cam.release()
cv2.destroyAllWindows()

I was not having problems with showing the live feed at first, but when I tried to run a different set of code that writes frames from the roi to an image path it lagged a lot and didn’t get the job done. The code that I ran for saving images is:

import os
import cv2
import time
import uuid
t,b,r,l = 250,470,450, 150
for light in lights:
!mkdir = {img_path+’\\’+light}
cam = cv2.VideoCapture(0)
print(‘Please perform the gesture: {}’.format(light))
time.sleep(3)
for i in range(num_img):
(ret,frame) = cam.read()
roi = frame[t:b,l:r]
cv2.rectangle(frame, (l,t), (r,b),(0,255,0),1)
cv2.imshow(‘frame’,frame)
imagename=os.path.join(img_path, light ,light +’.’+’{}.jpg’.format(str(uuid.uuid1())))
cv2.imwrite(imagename, frame)
cv2.imshow(‘roi’, roi)
time.sleep(2)
if cv2.waitKey(1) & 0xFF == ord(‘q’):
break
cam.release()
cv2.destroyAllWindows()

After this I restarted the kernel, cleared output then decided to simply run a basic video feed with no image saving in it. I am still getting a lot of lag in the webcam feed. I’m not having this lag issue when I try this code in Spyder.
Help would be appreciated.

Would you mind setting the code into backticks (`)? See GitLab Markdown | GitLab for more information on code formatting in Markdown. Currently your code is faulty because all indentions have been lost so it is difficult to comment on anything.Thanks!

1 Like