Giter Site home page Giter Site logo

srinivas-natarajan / animal-intrusion-alarm Goto Github PK

View Code? Open in Web Editor NEW
5.0 5.0 5.0 37.87 MB

An application which uses the camera to detect and identify animals, sounding an alert after their detection and emailing the owner about it

Python 41.11% Jupyter Notebook 58.89%
alarm animal-detection email python yolov3

animal-intrusion-alarm's People

Contributors

srinivas-natarajan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

animal-intrusion-alarm's Issues

Help me to create a new project using this resource

I want a one android app to receive the animal detected in the agricultural field. With send the captured image in the field not the configured images that we have.. i want a detected image from the field and send it to the app...

I have an error while run the detection.py in the pycharm pls help me solve this issue

Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py", line 63, in
yol = [yol[i[0] - 1] for i in net.getUnconnectedOutLayers()]
File "C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py", line 63, in
yol = [yol[i[0] - 1] for i in net.getUnconnectedOutLayers()]
IndexError: invalid index to scalar variable.

I am facing the below errors

My code:
import numpy as np
import time
import cv2
import os
import numpy as np
from playsound import playsound
import threading
import smtplib
import imghdr
from email.message import EmailMessage
import requests

def alert():
threading.Thread(target=playsound, args=('alarm.wav',), daemon=True).start()

def send_email(label, frame):

Sender_Email = "[email protected]"
Reciever_Email = "[email protected]"
# Password = input('Enter your email account password: ')
Password = 'xwmixxkvxgpnfrwj'   #ENTER GOOGLE APP PASSWORD HERE

newMessage = EmailMessage()    #creating an object of EmailMessage class
newMessage['Subject'] = "Animal Detected" #Defining email subject
newMessage['From'] = Sender_Email  #Defining sender email
newMessage['To'] = Reciever_Email  #Defining reciever email
emailBody = str(label)  +' has been detected.'
newMessage.set_content(emailBody) #Defining email body


image_data = frame
image_type = imghdr.what(frame.name)
image_name = label

newMessage.add_attachment(image_data, maintype='image', subtype=image_type, filename=image_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(Sender_Email, Password) #Login to SMTP server
    smtp.send_message(newMessage)      #Sending email using send_message method by passing EmailMessage object

def async_email(label):
threading.Thread(target=send_email, args=(label, frame), daemon=True).start()

args = {"confidence":0.5, "threshold":0.3}
flag = False

labelsPath = "./yolo-coco/coco.names"
LABELS = open(labelsPath).read().strip().split("\n")
final_classes = ['bird', 'cat', 'dog', 'sheep', 'horse', 'cow', 'elephant', 'zebra', 'bear', 'giraffe']

np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
dtype="uint8")

weightsPath = os.path.abspath("./yolo-coco/yolov3-tiny.weights")
configPath = os.path.abspath("./yolo-coco/yolov3-tiny.cfg")

print(configPath, "\n", weightsPath)

net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
ln = net.getLayerNames()
ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]

vs = cv2.VideoCapture('test1.mp4')
writer = None
(W, H) = (None, None)

flag=True

while True:
# read the next frame from the file
(grabbed, frame) = vs.read()

# if the frame was not grabbed, then we have reached the end
# of the stream
if not grabbed:
    break

# if the frame dimensions are empty, grab them
if W is None or H is None:
    (H, W) = frame.shape[:2]

blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),
    swapRB=True, crop=False)
net.setInput(blob)
start = time.time()
layerOutputs = net.forward(ln)
end = time.time()

# initialize our lists of detected bounding boxes, confidences,
# and class IDs, respectively
boxes = []
confidences = []
classIDs = []

# loop over each of the layer outputs
for output in layerOutputs:
    # loop over each of the detections
    for detection in output:
        # extract the class ID and confidence (i.e., probability)
        # of the current object detection
        scores = detection[5:]
        classID = np.argmax(scores)
        confidence = scores[classID]

        # filter out weak predictions by ensuring the detected
        # probability is greater than the minimum probability
        if confidence > args["confidence"]:
            # scale the bounding box coordinates back relative to
            # the size of the image, keeping in mind that YOLO
            # actually returns the center (x, y)-coordinates of
            # the bounding box followed by the boxes' width and
            # height
            box = detection[0:4] * np.array([W, H, W, H])
            (centerX, centerY, width, height) = box.astype("int")

            # use the center (x, y)-coordinates to derive the top
            # and and left corner of the bounding box
            x = int(centerX - (width / 2))
            y = int(centerY - (height / 2))

            # update our list of bounding box coordinates,
            # confidences, and class IDs
            boxes.append([x, y, int(width), int(height)])
            confidences.append(float(confidence))
            classIDs.append(classID)

# apply non-maxima suppression to suppress weak, overlapping
# bounding boxes
idxs = cv2.dnn.NMSBoxes(boxes, confidences, args["confidence"],
    args["threshold"])


# ensure at least one detection exists
if len(idxs) > 0:
    # loop over the indexes we are keeping
    for i in idxs.flatten():
        # extract the bounding box coordinates
        (x, y) = (boxes[i][0], boxes[i][1])
        (w, h) = (boxes[i][2], boxes[i][3])
        
        if(LABELS[classIDs[i]] in final_classes):
            #playsound('alarm.wav')
            if(flag):
                alert()
                flag=False
                async_email(LABELS[classIDs[i]])
            color = [int(c) for c in COLORS[classIDs[i]]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            text = "{}: {:.4f}".format(LABELS[classIDs[i]],
                confidences[i])
            cv2.putText(frame, text, (x, y - 5),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

else:
    flag=True

cv2.imshow("Output", frame) 

if cv2.waitKey(1) == ord('q'):
    break

release the webcam and destroy all active windows

vs.release()
cv2.destroyAllWindows()

ERRORS:
C:\Users\Administrator\AppData\Local\Programs\Python\Python38\python.exe C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py", line 32, in send_email
image_type = imghdr.what(frame.name)
AttributeError: 'numpy.ndarray' object has no attribute 'name'

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.
Exception in thread Thread-4:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py", line 32, in send_email
image_type = imghdr.what(frame.name)
AttributeError: 'numpy.ndarray' object has no attribute 'name'

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.
Exception in thread Thread-6:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py", line 32, in send_email
image_type = imghdr.what(frame.name)
AttributeError: 'numpy.ndarray' object has no attribute 'name'

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-5:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.

Process finished with exit code 0

I facing errors while passing the parameter as the frame

I changed code as you told as

def send_email(label, frame):

Sender_Email = "@gmail.com"
Reciever_Email = "@gmail.com"
# Password = input('Enter your email account password: ')
Password = ''   #ENTER GOOGLE APP PASSWORD HERE

newMessage = EmailMessage()    #creating an object of EmailMessage class
newMessage['Subject'] = "Animal Detected" #Defining email subject
newMessage['From'] = Sender_Email  #Defining sender email
newMessage['To'] = Reciever_Email  #Defining reciever email
emailBody = str(label)  +' has been detected.'
newMessage.set_content(emailBody) #Defining email body

with open('images/' + label + '.png' , 'rb') as f:
image_data = frame
image_type = imghdr.what(frame.name)
image_name = label

newMessage.add_attachment(image_data, maintype='image', subtype=image_type, filename=image_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(Sender_Email, Password) #Login to SMTP server
    smtp.send_message(newMessage)      #Sending email using send_message method by passing EmailMessage object

def async_email(label, frame):
threading.Thread(target=send_email, args=(label, frame), daemon=True).start()
############################################
but facing I am facing errors..pls help me to resolve it..

ERRORS

File "C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py", line 35
newMessage.add_attachment(image_data, maintype='image', subtype=image_type, filename=image_name)
^
IndentationError: unindent does not match any outer indentation level

Process finished with exit code 1

How to change email body image

While you detecting the animals in the field you sending the configured animal image regarding the animal detected like this below:

29f539aa-2f6d-4871-a074-206a0392bac4

I want to sent the email body alert with the detected animal image in the field with their name like this below:

76e20c40-207d-47d0-9e42-2cb9472fc93a

Please Help to update the project with this changes as soon as possible and also pls guide me

Pls help me to resolve the issue

the audio file not playing while multiple animal detection and in a single frame only one animal detected and very slow while detecting.. and also i am facing the below errors while detecting the animal

####################
Error 263 for command:
close alarm.wav
The specified device is not open or is not recognized by MCI.
Failed to close the file: alarm.wav

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-5:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-7:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-9:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav

Error 259 for command:
    play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav
Exception in thread Thread-19:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 73, in _playsoundWin
winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 259 for command:
play alarm.wav wait
The driver cannot recognize the specified command parameter.

Error 263 for command:
    close alarm.wav
The specified device is not open or is not recognized by MCI.

Failed to close the file: alarm.wav

I am facing the error while remove the as you told the line of code

Code:

def send_email(label, frame):

Sender_Email = "[email protected]"
Reciever_Email = "[email protected]"
# Password = input('Enter your email account password: ')
Password = 'xwmixxkvxgpnfrwj'   #ENTER GOOGLE APP PASSWORD HERE

newMessage = EmailMessage()    #creating an object of EmailMessage class
newMessage['Subject'] = "Animal Detected" #Defining email subject
newMessage['From'] = Sender_Email  #Defining sender email
newMessage['To'] = Reciever_Email  #Defining reciever email
emailBody = str(label)  +' has been detected.'
newMessage.set_content(emailBody) #Defining email body


    image_data = frame
    image_type = imghdr.what(frame.name)
    image_name = label

newMessage.add_attachment(image_data, maintype='image', subtype=image_type, filename=image_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(Sender_Email, Password) #Login to SMTP server
    smtp.send_message(newMessage)      #Sending email using send_message method by passing EmailMessage object

def async_email(label, frame):
threading.Thread(target=send_email, args=(label, frame), daemon=True).start()

###############################

facing error:

C:\Users\Administrator\AppData\Local\Programs\Python\Python38\python.exe C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py
File "C:/Users/Administrator/Desktop/Animal-Intrusion-Alarm-main/detection.py", line 31
image_data = frame
^
IndentationError: unexpected indent

Process finished with exit code 1

pls help me to resolve it bro...

Detected animal label

newMessage.set_content('An animal has been detected') #Defining email body

in the email body i want to send the message with the detected animal name .. like this "DOG HAS BEEN DETECTED" or "DEER HAS BEEN DETECTED" regarding the animal detected the label must be change ..so pls help me the build the project with the issues i posted below and here thank you for you time and support for me..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.