import cv2
from ultralytics import YOLO
#import secret
import threading
import time
W=1280
H=720
#Now, as eplained in the video, edit the line below where
#you put your wifi user name in place of user, and your
#wifi password in place of password, and you put in your
#IP address
RTSP_URL = "rtsp://user:password@192.168.88.44:554/cam/realmonitor?channel=1&subtype=0"
#RTSP_URL = secret.RTSP_URL1
#I have put my wifi credentials in a secret file so no
#one sees my credentials. You will just use the RTSP_URL line above.
# Load the exported NCNN model (replace with your model path)
model = YOLO("/home/pjm/yolo11n_ncnn_model/", task="detect")
lock = threading.Lock()
running = True
def frameGrabber(url):
global ipFrame, running
cap = cv2.VideoCapture(url, cv2.CAP_FFMPEG)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # Reset frame position
while running:
ret, frame = cap.read()
if ret:
with lock:
#frame = cv2.resize(frame, (W, H))
ipFrame = frame.copy()
cap.release()
print("Thread Terminated")
thread = threading.Thread(target=frameGrabber, args=(RTSP_URL,), daemon=True)
thread.start()
tStart=time.time()
time.sleep(2)
fps=0
cnt=0
# Set resolution for faster processing (optional, adjust based on your needs)
while True:
deltaT=time.time()-tStart
fps= fps*.9 + .1/deltaT
tStart=time.time()
with lock:
ipFrameShow=ipFrame.copy()
results = model(ipFrameShow, conf=0.25, verbose=False)[0] # conf: confidence threshold; adjust as needed
# Annotate the frame with detections (boxes, labels, scores)
annotatedFrame = results.plot()
annotatedFrame=cv2.resize(annotatedFrame, (W,H))
cv2.putText(annotatedFrame, "FPS: "+str(round(fps,1)), (int(W*.01), int(H*.075)),
cv2.FONT_HERSHEY_SIMPLEX, H*.002, (0, 0, 255), 3)
cv2.imshow("IP Camera", annotatedFrame)
#cv2.moveWindow("IP Camera",100,100)
if cv2.waitKey(1)==ord('q'):
break
running=False
thread.join() # Wait for thread to fully exit
time.sleep(1)
cv2.destroyAllWindows()
import gc
gc.collect() # Force garbage collection to reclaim memory/connections
#Make Extra sure all processes are killed
import os
os._exit(0)
print("Program Terminated")