OpenCV : cap.read() doesnt read frames from live camera feed after few frames

26 views Asked by At

I am trying to read live camera feed and detect the object using Yolov8 and CV2. It works with web cam but when I supply rtsp url it works for few frames and then not able to read frames. If i read rtsp without any processing then it works.

Here is code.

from ultralytics import YOLO
import cv2
rtsp_url = "url"
cap = cv2.VideoCapture(rtsp_url)
model = YOLO("../Yolo-Weights/yolov8l.pt")
classNames = ["person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat"]
if not cap.isOpened():
    print("Error: Could not open RTSP stream.")
    exit()

myColor = (0, 0, 255)
while True:
    success, img = cap.read()
    if not success or img is None or img.size == 0:
        print("Error: Could not read frame.")
        continue
    resized_frame = cv2.resize(img, (800, 600))
    results = model(resized_frame, stream=True)
    for r in results:
        boxes = r.boxes
        for box in boxes:
            # Bounding Box
            x1, y1, x2, y2 = box.xyxy[0]
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
            # cv2.rectangle(img,(x1,y1),(x2,y2),(255,0,255),3)
            w, h = x2 - x1, y2 - y1
            # cvzone.cornerRect(img, (x1, y1, w, h))

            # Confidence
            conf = math.ceil((box.conf[0] * 100)) / 100
            # Class Name
            cls = int(box.cls[0])
            currentClass = classNames[cls]
            # if conf > 0.5:
                # if currentClass == 'NO-Hardhat' or currentClass == 'NO-Safety Vest' or currentClass == "NO-Mask":
                #     myColor = (0, 0, 255)
                # elif currentClass == 'Hardhat' or currentClass == 'Safety Vest' or currentClass == "Mask":
                #     myColor = (0, 255, 0)
                # else:
            myColor = (255, 0, 0)

            cvzone.putTextRect(img, f'{classNames[cls]} {conf}',
                               (max(0, x1), max(35, y1)), scale=1, thickness=1, colorB=myColor,
                               colorT=(255, 255, 255), colorR=myColor, offset=5)
            cv2.rectangle(img, (x1, y1), (x2, y2), myColor, 3)

    cv2.imshow("Image", resized_frame)
    cv2.waitKey(1)

If I remove for loop of boxes & results it will work else after few frames it will give "Error: Could not read frame."

I want it should detect object from live feed continously as I checked camera is working fine.

0

There are 0 answers