Skip to main content

sdsfd

from ultralytics import YOLO

import cv2

import BlynkLib

import time

from datetime import datetime

import requests


# Blynk Configuration

BLYNK_AUTH = "YOUR_BLYNK_AUTH_TOKEN"  # Replace with your Blynk auth token

BLYNK_SERVER = "blynk.cloud"


# Initialize Blynk

blynk = BlynkLib.Blynk(BLYNK_AUTH)


# Virtual Pins

VPIN_ALERT = 0          # V0 - Alert text display

VPIN_DETECTION_LED = 1  # V1 - LED indicator

VPIN_LAST_SEEN = 2      # V2 - Last detection timestamp

VPIN_ANIMAL_COUNT = 3   # V3 - Number of animals detected

VPIN_IMAGE = 4          # V4 - Image widget for detection snapshots


# Load YOLO model

model = YOLO("yolov8n.pt")


# Animal classes to detect

animal_classes = {

    0: "person",

    14: "bird",

    15: "cat",

    16: "dog",

    17: "horse",

    18: "sheep",

    19: "cow",

    20: "elephant",

    21: "bear"

}

animal_ids = list(animal_classes.keys())


# Initialize webcam (USB webcam on Raspberry Pi)

cap = cv2.VideoCapture(0)


# Set camera resolution (lower for better performance on Pi)

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)

cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)


print("Animal Detection System Started on Raspberry Pi")

print("Press Ctrl+C to exit")


last_alert_time = 0

alert_cooldown = 2  # Send Blynk alert every 2 seconds max


def send_image_to_blynk(frame):

    """Send captured image to Blynk when animal detected"""

    try:

        # Encode frame to JPEG with compression for faster upload

        _, buffer = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 70])

        

        # Save temporarily

        filename = "/tmp/detection.jpg"

        with open(filename, 'wb') as f:

            f.write(buffer)

        

        # Upload to Blynk

        url = f"https://{BLYNK_SERVER}/external/api/upload/image"

        with open(filename, 'rb') as img_file:

            files = {'image': img_file}

            data = {'token': BLYNK_AUTH, 'pin': f'V{VPIN_IMAGE}'}

            response = requests.post(url, files=files, data=data, timeout=5)

        

        if response.status_code == 200:

            print("  ✓ Image uploaded to Blynk")

        else:

            print(f"  ✗ Failed to upload image: {response.status_code}")

    except Exception as e:

        print(f"  ✗ Error uploading image: {e}")


try:

    while True:

        # Run Blynk

        blynk.run()

        

        ret, frame = cap.read()

        if not ret:

            print("Failed to grab frame from webcam")

            time.sleep(1)

            continue


        # Run YOLO detection

        results = model(frame, classes=animal_ids, verbose=False)


        intruder_detected = False

        detected_labels = []


        # Process detections

        for box in results[0].boxes:

            cls_id = int(box.cls[0])

            if cls_id in animal_classes:

                intruder_detected = True

                detected_labels.append(animal_classes[cls_id])


        # Handle detection alerts

        current_time = time.time()

        if intruder_detected:

            detected_labels = list(set(detected_labels))

            alert_text = "INTRUDER: " + ", ".join(detected_labels)

            animal_count = len(detected_labels)

            

            # Send to Blynk (with cooldown to avoid spam)

            if current_time - last_alert_time > alert_cooldown:

                blynk.virtual_write(VPIN_ALERT, alert_text)

                blynk.virtual_write(VPIN_DETECTION_LED, 255)  # Turn on LED

                blynk.virtual_write(VPIN_ANIMAL_COUNT, animal_count)

                blynk.virtual_write(VPIN_LAST_SEEN, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

                blynk.log_event("animal_detected", alert_text)  # Create "animal_detected" event in Blynk

                

                # Send snapshot to Blynk

                send_image_to_blynk(frame)

                

                last_alert_time = current_time

                

            print(f"[{datetime.now().strftime('%H:%M:%S')}] {alert_text}")

        else:

            # No detection - turn off LED

            blynk.virtual_write(VPIN_DETECTION_LED, 0)

            blynk.virtual_write(VPIN_ALERT, "No intruders")

            blynk.virtual_write(VPIN_ANIMAL_COUNT, 0)


        # Small delay to reduce CPU usage

        time.sleep(0.1)


except KeyboardInterrupt:

    print("\nShutting down...")


finally:

    cap.release()

    print("Camera released. Exiting.") 

Comments

Popular posts from this blog

ഇടുക്കി - അയ്യപ്പൻകോവിൽ തൂക്കുപാലം. Ayyappankovil hanging bridge in Malayalam

ഇടുക്കി ജില്ലയിലെ കാഞ്ചിയാർ - അയ്യപ്പൻകോവിൽ പഞ്ചായത്തുകളെ തമ്മിൽ ബന്ധിച്ചുകൊണ്ട് നിലനിൽക്കുന്നു. ഇടുക്കി ജില്ലയിലെ ഏറ്റവും വലിയ തൂക്കുപാലമാണിത്.  2013 ൽ ഇടുക്കി ജലാശയത്തിന് കുറുകേയാണ് ഈ തൂക്കുപാലം നിർമ്മിച്ചത്. 200 മീറ്റർ നീളത്തിൽ സ്ഥിതി ചെയ്യുന്ന അയ്യപ്പൻകോവിൽ  തൂക്കുപാലം സഞ്ചരികളുടെ മനം കവര്‍ന്നു. വർഷകാലത്ത് നിറഞ്ഞു കിടക്കുന്ന ജലാശയത്തിന് മീതെയായും വേനൽകാലത്ത് വെള്ളം ഇറങ്ങി കഴിഞ്ഞു കാണുന്ന പുൽമേടുകൾക്ക് മീതെയായും നിൽക്കുന്ന തൂക്കുപാലം കണ്ണിനും മനസ്സിനുംഒരുപോലെ സന്തോഷം പകരുന്നു.  

Chokramudi Peak || short blog || Yathrakal ishtam

 Chokramudi Peak is the one of the highest peak in Idukki, Kerala at the elevation of 7300 ft. Located in the Eravikulam national park between bisonvalley and munnar.    This peak provides a beautiful view of the surrounding valley, mountains covered with dense forest and tea plantation. Also an amazing view of anamudi peak and Idukki dam. That's an unforgettable experience. Chokramudi Trek is very short and easy trek that can be done in a day. The starting point of the trek is near from bisonvalley. From here, the trek can be of 4 to 6 hours to covering a distance of 10km upwards.   Months of December to February is the best time to trek anywhere in munnar. The breezing atmosphere and the chilling cold gives you an unforgettable memory.

ഇന്ത്യയുടെ ആത്മീയ തലസ്ഥാനം-ഋഷികേശ് |Yathrakal ishtam| spiritual capital of India Rishikesh in Malayalam

Kedarnath temple Photo courtesy insta@ keraliann വടക്കൻ ഉത്തരാഖണ്ഡിലെ ഒരു നഗരമാണ് ഋഷികേശ്. ഹിമാലയൻ മലനിരകൾ അതിരിട്ടു നിൽക്കുന്ന താഴ് വരയിൽ പുണ്ണ്യനദിയായ ഗംഗയുടെ തീരത്താണ് ഋഷികേശ് സ്ഥിതി ചെയ്യുന്നത്. നൂറിലധികം ക്ഷേത്രങ്ങളും യോഗ കേന്ദ്രങ്ങളും, പ്രകൃതി മനോഹാരിതയുമാണ് ഈ സ്ഥലത്തെ സവിശേഷമാക്കുന്നത്     കേദാർനാഥ്, ബദരീനാഥ്, ഗംഗോത്രി, യമുനോത്രി എന്നീ ക്ഷേത്രങ്ങളിലേക്കുള്ള  യാത്ര ആരംഭിക്കുന്നത് ഇവിടെ നിന്നാണ്. പണ്ട് കാലത്ത് ഋഷിവര്യന്മാർ ശാന്തമായ ഗംഗയുടെ തീരത്ത് തപസ്സ് ചെയ്യതിരുന്നതായി പറയപ്പെടുന്നു. യോഗ കാപ്പിറ്റൽ എന്ന് അറിയപ്പെടുന്നത് ഋഷികേശാണ്. ഒരുപാടത്തികം യോഗ കേന്ദ്രങ്ങൾ ഇവിടെ പ്രവർത്തിച്ചുവരുന്നുണ്ട്. ആദ്യകാലത്ത് ആത്മീയത തേടിയായിരുന്നു ഏറ്റവുമധികം ആളുകൾ ഇവിടെ എത്തിച്ചേരുന്നത്. ഇപ്പോൾ ആത്മീയതക്ക് പുറമെ ടൂറിസവും പച്ച പിടിച്ചിട്ടുണ്ട്.     ഗംഗയിലുടെയുള്ള റിവർ റാഫ്ടിംഗ്, പാരാഗ്ലൈടിംഗ്, കായാക്കിങ്, ബൻജി ജംമ്പിങ്,  ക്യാമ്പിങ്. ഇത്തരത്തിലുള്ള നിരവധി സാഹസിക പ്രവർത്തനങ്ങൾ സഞ്ചാരികളെ ആകർഷിക്കുന്നുണ്ട്.