In your code, you are overwriting one image multiple times. Every single found movement contour wites image again.
This code shoud solve your problem:
import cv2
import imutils
import time
cap = cv2.VideoCapture(“rtsp://admin:a10b20c30d40@192.168.0.116:554/cam/realmonitor?channel=1&subtype=2”)
ret, frame1 = cap.read()
ret, frame2 = cap.read()
// Flag, if movement was detected in last frame
lastFound = False
while cap.isOpened():
ts = time.time()
diff = cv2.absdiff(frame1,frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
movement = False
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
if cv2.contourArea(contour) < 199900:
continue
movement = True
cv2.rectangle(frame1, (x,y), (x+w, y+h), (0, 255, 0), 2)
// Write image if movement was detected and no movement was in previous frame
if movement and not lastFound:
lastFound = True
cv2.putText(frame1, "status: {}".format('Movement'), (10, 20),
cv2.FONT_HERSHEY_SIMPLEX,
1, (0, 0, 255), 3)
cv2.imwrite('C:\\Users\\Administrador\\Desktop\\picture\\' + str(ts) + '.png', frame1)
// Clear last detected flag
if not movement:
lastFound = False
resized = imutils.resize(frame1, width=600)
cv2.imshow('feed', resized)
frame1 = frame2
ret, frame2 = cap.read()
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyWindow()