Search code examples
pythonpython-3.xipip-camera

How can I do IP camera connection verification


I have a code block like the one below, but I cannot verify connection. If the camera cannot be connected, I want to print a connection error. Can you help me.

import numpy as np
import cv2
cap = cv2.VideoCapture('rtsp://admin:12345678@192.168.102.114:554/ch01_sub.264')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('ouput.avi', fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        frame = cv2.flip(frame,0)
        out.write(frame)
        
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
           break
    else:
       break

cap.release()
out.release()
cv2.destroyAllWindows()

Solution

  • Try using try. The below code may not be exactly correct as I don't quite understand where it is failing, but should give you enough to get the idea.

        try: 
            while(cap.isOpened()):
    
               ret, frame = cap.read()
               frame = cv2.flip(frame,0)
               out.write(frame)
            
               cv2.imshow('frame',frame)
    
               if cv2.waitKey(1) & 0xFF == ord('q'):
                 break
    
        except: 
            print('Connection error')