found a working code now. had to rephrase my query with Claude.ai for it to give the right answer.
here's the code in case anyone ever need. the pi camera is embeded in a Smart Mirror. when motion is detected, turn relay on to turn TV panel within the mirror on. relay pin on gpio 17. after 1 min, 60 seconds in code below, if no motion then turn relay to Off.
here's the code in case anyone ever need. the pi camera is embeded in a Smart Mirror. when motion is detected, turn relay on to turn TV panel within the mirror on. relay pin on gpio 17. after 1 min, 60 seconds in code below, if no motion then turn relay to Off.
Code:
import timefrom picamera2 import Picamera2import cv2import numpy as npimport RPi.GPIO as GPIO# Set up GPIORELAY_PIN = 17GPIO.setmode(GPIO.BCM)GPIO.setup(RELAY_PIN, GPIO.OUT)# Initialize the camerapicam2 = Picamera2()config = picam2.create_preview_configuration(main={"size": (640, 480)})picam2.configure(config)picam2.start()# Initialize variables for motion detectionprev_frame = Nonemotion_detected = Falselast_motion_time = time.time()def detect_motion(frame): global prev_frame # Convert frame to grayscale and blur it gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) # If this is the first frame, initialize it and return if prev_frame is None: prev_frame = gray return False # Compute the absolute difference between the current frame and the previous frame frame_delta = cv2.absdiff(prev_frame, gray) thresh = cv2.threshold(frame_delta, 25, 255, cv2.THRESH_BINARY)[1] # Dilate the thresholded image to fill in holes, then find contours thresh = cv2.dilate(thresh, None, iterations=2) contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Check if any contour is large enough to be considered motion for contour in contours: if cv2.contourArea(contour) > 900: # Adjust this threshold as needed prev_frame = gray return True prev_frame = gray return Falsetry: while True: # Capture frame frame = picam2.capture_array() # Detect motion if detect_motion(frame): motion_detected = True last_motion_time = time.time() GPIO.output(RELAY_PIN, GPIO.HIGH) # Turn relay ON print("Motion detected! Relay ON") elif motion_detected and (time.time() - last_motion_time) > 60: # 60 seconds = 1 minute motion_detected = False GPIO.output(RELAY_PIN, GPIO.LOW) # Turn relay OFF print("No motion for 1 minute. Relay OFF") time.sleep(0.1) # Small delay to reduce CPU usageexcept KeyboardInterrupt: print("Stopping the script...")finally: GPIO.cleanup() picam2.stop()
Statistics: Posted by tung256 — Thu Sep 19, 2024 1:04 am