Camera only shows first frame, then it becomes slow and then it completely freezes. How can I optimize my code so that camera is fast?
import cv2
import numpy as np
from serial.tools import list_ports
import csv
import time
from PIL import Image
from imutils.video import FileVideoStream
from imutils.video import FPS
import imutils
def find_contours(frame):
belt = frame[145:440, :]
gray_belt = cv2.cvtColor(belt, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray_belt, 20, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return contours, threshold, belt
def find_colors(frame):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
rows,cols,_ = frame.shape
for x in range(rows):
for y in range(cols):
pixel = frame[x,y]
hue = pixel[0]
saturation = pixel[1]
lightness = pixel[2]
if lightness <= 127.5:
frame[x,y][0] = 0
elif lightness >127.5:
frame[x,y][2] = 225
if saturation <= 127.5:
frame[x,y][1] = 0
elif saturation >127.5:
frame[x,y][1] = 225
cv2.imshow('enhanced', frame)
lower_red = np.array([0, 0, 0])
upper_red = np.array([255, 150, 150])
mask = cv2.inRange(frame, lower_red, upper_red)
frame[mask==0] = [0,0,0]
frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR)
return frame
fvs = FileVideoStream(1).start()
time.sleep(1)
fps = FPS().start()
sub_background = cv2.createBackgroundSubtractorMOG2(history=0, varThreshold=444, detectShadows=False)
while fvs.more():
frame = fvs.read()
trasformed = find_colors(frame)
cv2.imshow('trasformed', trasformed)
contours, threshold, belt = find_contours(frame)
for cnt in contours:
(x, y, w, h) = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
if area > 3000:
x_center = int(x + (w/2))
y_center = int(y + (h/2))
cv2.rectangle(belt, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.circle(belt, (x_center, y_center), 2,(0, 128, 255), 2)
cv2.imshow("frame", frame)
cv2.imshow("threshold", threshold)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
fps.update()
fps.stop()
cv2.destroyAllWindows()
fvs.stop()
↧