Raspberry Pi + camera wifi

Bonjour,
J’ai installé open Cv sur mon Raspberry Pi4 4gb . j’ai commencé un script sur python permettant la détection et l’enregistrement de vidéo capturée avec une caméra Avidsen ( mon réseau est constitué du Raspberry sur box en Ethernet, camera en wifi sur box ) . Le script fonctionne bien (lecture , détection et enregistrement). Je suis néanmoins confronté à un problème que je ne comprends pas, il me manque des images et la progression dans le temps n’est pas cohérent.
Par exemple sur un test simple ou je présente devant la camera ma main qui va décompter avec les doigts le temps ( 5 secondes ) la détection se fait correctement. Cependant lorsque je visualise le film je vois mon doigt représentant la premiere seconde , puis très rapidement ma main qui se retire du champ de la caméra sans voir les autres secondes ( parfois mais rarement je vois la 3eme seconde ).
Pour information lorsque ce script est utilisé sur l’environnement de mon pc Windows l’enregistrement est cohérent en temps et en images ?
Avez-vous une idée pour ce problème?
Merci de votre retour et bonne année 2024
François

you should edit your post and replace that by an english translation

hi,
I installed OpenCv on my Raspberry Pi4 4gb. I wrote a simple script with python allowing the detection and recording of video captured with an Avidsen camera (my network consists of Raspberry connected on box in Ethernet, camera in wifi on box also). The script works well (reading, detection and recording). However, I am confronted with a problem that I do not understand, I am missing images and the progression over time is not consistent.
For example, on a simple test where I present my hand in front of the camera which will count down the time with my fingers (5 seconds), the detection is done correctly. However, when I watch the film I see the finger representing the first second, then very quickly my hand which withdraws from the camera field without seeing the other seconds (sometimes but rarely I see the 3rd second).
For information, when this script is used on my Windows computer environment, the recording is consistent in time and images. May be the problem is du to the Raspberry or version OpenCv with this configuration.

My Os on raspberry
PRETTY_NAME=“Raspbian GNU/Linux 11 (bullseye)”
NAME=“Raspbian GNU/Linux”
VERSION_ID=“11”
VERSION=“11 (bullseye)”
VERSION_CODENAME=bullseye
ID=raspbian
ID_LIKE=debian

My python version :Python 3.9.2

my OpenCv version with my Raspbian platform when i use pkg-config

              libopencv-calib3d4.5:armhf           4.5.1+dfsg-5
              libopencv-contrib4.5:armhf            4.5.1+dfsg-5
              libopencv-core4.5:armhf               4.5.1+dfsg-5
              libopencv-dnn4.5:armhf                4.5.1+dfsg-5
              libopencv-features2d4.5:armhf         4.5.1+dfsg-5
              libopencv-flann4.5:armhf              4.5.1+dfsg-5
              libopencv-highgui4.5:armhf            4.5.1+dfsg-5
              libopencv-imgcodecs4.5:armhf          4.5.1+dfsg-5
              libopencv-imgproc4.5:armhf            4.5.1+dfsg-5
              libopencv-ml4.5:armhf                 4.5.1+dfsg-5
              libopencv-objdetect4.5:armhf          4.5.1+dfsg-5
              libopencv-photo4.5:armhf              4.5.1+dfsg-5
              libopencv-shape4.5:armhf              4.5.1+dfsg-5
              libopencv-stitching4.5:armhf          4.5.1+dfsg-5
              libopencv-videoio4.5:armhf            4.5.1+dfsg-5

Do you have any idea for this problem?
I am a novice to this particular topic…

Thank you for your feedback and happy new year 2024
Francois

MRE must include source code

Hi
You will find bellow my source code


import cv2 
import time 
import datetime 
import paramiko 

ssh_file="/home/*****/****/*******"

url_cam="rtsp://****:****@192.168.***.***:554/mode=real&idc=1&ids=1"

remote_path='/home/****/*****/******/Images/'

host = "192.168.***.***"
user = "*****"
pswd = "*****"


ssh_client = paramiko.SSHClient()

ssh_client.connect(hostname=str(host),username =str(user),password=str(pswd))

cap = cv2.VideoCapture(url_cam)

fps = cap.get(cv2.CAP_PROP_FPS)
print(fps)
width  = cap.get(cv2.CAP_PROP_FRAME_WIDTH)   # float
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # float

mog = cv2.createBackgroundSubtractorMOG2()

detection = False
detection_stopped_time = None
timer_started = False

SECONDS_TO_RECORD_AFTER_DETECTION = 5

frame_size = (int(cap.get(3)), int(cap.get(4)))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
#fourcc = cv2.VideoWriter_fourcc(*'MPV4')

while True:
    
    cv2.namedWindow("Camera", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("Camera", 1000, 500)
    
    ret, frame = cap.read()
    
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      
    fgmask = mog.apply(gray)

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    fgmask = cv2.erode(fgmask, kernel, iterations=1)
    fgmask = cv2.dilate(fgmask, kernel, iterations=1)
    
    
    contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    
    if len(contours) > 100: 
    
        if detection:
           
            timer_started = False 
        else:
            
            detection = True
            current_time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%Y-%m-%d")
            
            out = cv2.VideoWriter(
                f"{current_time}.avi", fourcc, fps, (int(width), int(height)))
            print("Started Recording!")
            print(len(contours))
            
            sftp_client = ssh_client.open_sftp()
    
    elif detection:
        if timer_started:
           
            if time.time() - detection_stopped_time >= SECONDS_TO_RECORD_AFTER_DETECTION:
                print("boucle de fermeture")
                print(len(contours))
                
                detection = False
                timer_started = False
                
                out.release()
                print('Stop Recording!')
                
                local_file_path = f"{current_time}.avi"
                remote_file_path = f"{remote_path}{current_time}.avi"
                
                sftp_client.put(local_file_path, remote_file_path)
                
                sftp_client.close()
                
        else:
            timer_started = True
            detection_stopped_time = time.time()
            print("boucle ouverture en cours ")
    if detection:
        out.write(frame)
    
    for contour in contours:
        
        if cv2.contourArea(contour) < 1000:
            continue
        
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    
    cv2.imshow("Camera", frame) 
	
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
ssh_client.close()

Regards
François

this is not guaranteed to be accurate or meaningful. especially on streaming video, the video feed may not have a fixed rate.

do you expect this to be true for the entire input?

there is an appreciable amount of code that has no bearing on the issue. please review MRE.

hi crackwitz
In summary to be clearer and simpler about my expectations, I want to record the video when the len(contours) >100 up to 10 seconds after len(contours) lower than 100.

hi
I thought this point was easy to solve but it seems not.
I’m going to forget the raspberry pi and work with the computer based in windows environnement, it’s simpler and my code works without the problem regarding the saving mode .
regards
françois