I am using YOLO video analysis and have two flask pages, the first shows the raw video stream and the second shows the stream with associated boxes from YOLO analysis. When i move through the flask page from the video stream page to the analysis page the video stream on both pages works. When i move back from the analysis page to the raw video stream page i get the following error
'CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072873821'
Code is as follows for YOLO analysis stream:
def yolo_stream():
model = YOLO('yolo_training/foam_model.pt')
cap = cv2.VideoCapture(camera_in_use)
df_tank1 = pd.DataFrame(columns=['date', 'name', 'name', 'name', 'name'])
while True:
ret, frame = cap.read()
if ret:
df_tank1 = df_tank1.append({'date': datetime}, ignore_index=True)
results = model(frame, show=False, conf=0.4, save=False)
print (f'len of results: {(len(results))}')
for r in results:
boxes=r.boxes
for box in boxes:
# setting up the boxes in the video frames
x1,y1,x2,y2=box.xyxy[0]
print('tensor coordinates of box: ', x1, y1, x2, y2) # prints tensors get it to print the integer box corners
x1,y1,x2,y2=int(x1), int(y1), int(x2), int(y2)
print("int coordinates of box: " ,x1,y1,x2,y2) # this one should not show the tensor numbers, use this to get the area of the boxes which will then be graphed
cv2.rectangle(frame, (x1,y1), (x2,y2), (255,0,255),3)
conf=math.ceil((box.conf[0]*100))/100
cls=int(box.cls[0])
class_name=classNames[cls]
label=f'{class_name}{conf}'
area_in_box = (x2-x1)*(y2-y1)
print(f'area in {class_name} box: ', area_in_box)
t_size = cv2.getTextSize(label, 0, fontScale=1, thickness=2)[0]
c2 = x1 + t_size[0], y1 - t_size[1] - 3
cv2.rectangle(frame, (x1,y1), c2, [255,0,255], -1, cv2.LINE_AA) # filled
cv2.putText(frame, label, (x1,y1-2),0, 1,[255,255,255], thickness=1,lineType=cv2.LINE_AA)
# creating the graph and a pd data frame for holding the box values and adds values
if area_in_box:
df_tank1 = df_tank1.append({class_name: int(area_in_box)}, ignore_index=True) # functional with readouts in cmd
# actual generation of the frame on the page
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n' )
else:
break
cap.release()
code for raw video stream:
def generate_frames():
while True:
success, frame = cap.read()
if not success:
break
else:
# dipslaying the frame
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')