ANIMAL INTRUSION DETECTION

PHOTO EMBED

Sun Jul 30 2023 11:06:17 GMT+0000 (Coordinated Universal Time)

Saved by @sukumar #python

#Import packages
import numpy as np
#import argparse
import cv2
import random
import pygame
from email.message import EmailMessage
import imutils
import time
import datetime
import imghdr
import os
from collections import Counter
import playsound
import requests
from playsound import playsound
#from imutils.video import VideoStream
from imutils.video import FPS
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# construct the argument parse and parse the arguments
#ap = argparse.ArgumentParser()
#ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file")
#ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model")
#ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
#args = vars(ap.parse_args())

protext="DNN_Object_Detection-master/DNN_Object_Detection-master/MobileNetSSD_deploy.prototxt.txt"
model="DNN_Object_Detection-master/DNN_Object_Detection-master/MobileNetSSD_deploy.caffemodel"

	# initialize the list of class labels MobileNet SSD was trained to
	# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
REQ_CLASSES=["bird","cat","cow","dog","horse","sheep"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

	#Load model
print("Loading Model...")
net=cv2.dnn.readNetFromCaffe(protext, model)
print("Starting camera feed...")

vs=cv2.VideoCapture(0, cv2.CAP_DSHOW)
	#vs=VideoStream(src=0).start()
time.sleep(2)
fps=FPS().start()

	#Set confidence threshold
conf_thresh=0.2

	#Animal detection counter
count=[]
flag=0
siren_loc=os.path.join(os.getcwd(),'Siren.wav')
global det
det=0
	#Read frame by frame
while vs:
	success, frame = vs.read()
	if not success:
		break
	frame = imutils.resize(frame, width=500)
	#Take the frame dimentions and convert it to a blob
	(h, w) = frame.shape[:2]
	blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300,300)), 0.007843, (300,300), 127.5)

	net.setInput(blob)
	detections = net.forward()
	#frame detection flag
	for i in np.arange(0, detections.shape[2]):
		#Probability associated with predictions
		confidence = detections[0,0,i,2]
		if confidence > conf_thresh:
			#Extract the class labels and dimentions of bounding box
			idx = int(detections[0,0,i,1])
			box = detections[0,0,i,3:7]*np.array([w,h,w,h])
			(startX, startY, endX, endY) = box.astype("int")

			#draw the box with labels
			if CLASSES[idx] in REQ_CLASSES:
				det+=1
				label="{}: {:.2f}%".format("Animal",confidence*100)
				cv2.rectangle(frame, (startX, startY), (endX, endY), (36,255,12), 2)
				if (startY-15) > 15:
					y = (startY - 15)
				else:
					y = (startY+15)
				print(f"Animal Intrusion Alert...!!! {len(count)}")
				path = r"siren/alert"
				file = os.path.join(path, random.choice(os.listdir(path)))
				pygame.mixer.init()
				pygame.mixer.music.load(file)
				pygame.mixer.music.play()
				if det >=10:
					nn = random.randint(0, 100)
					noOfFile = 'Animal' + str(nn) + '.jpg'
					print(type(noOfFile))
					cv2.imwrite("static/Animal_data/" + noOfFile, frame[startY:endY, startX:endX])
					ts = time.time()
					date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
					timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
					s1 = "a@gmail.com"
					msg = 'Hi countryman!!'
					msg1 = 'We have captured an animal in your forms at ' + timeStamp + ' on ' + date + ' please be safe. '
					t = 'Regards,'
					t1 = 'AI Farming Services.'
					mail_content1 = msg + ',' + '\n' + msg1 + '\n' + '\n' + t + '\n' + t1
					sender_address = 'dopatisukumar@gmail.com'
					sender_pass = 'rzihvvowxagwrwgd'
					receiver_address = 'sukumardopati@gmail.com'
					message1 = MIMEMultipart()
					message1['From'] = sender_address
					message1['To'] = receiver_address
					message1['Subject'] = 'Animal Detection Using OpenCV'
					message1.attach(MIMEText(mail_content1, 'plain'))
					session2 = smtplib.SMTP('smtp.gmail.com', 587)
					session2.starttls()
					session2.login(sender_address, sender_pass)
					text1 = message1.as_string()
					session2.sendmail(sender_address, receiver_address, text1)
					session2.quit()

					newMessage = EmailMessage()
					newMessage['Subject'] = "Animal Detection Using OpenC"
					newMessage['From'] = sender_address
					newMessage['To'] = receiver_address
					newMessage.set_content(mail_content1)

					with open('static/Animal_data/' + noOfFile, 'rb') as f:
						image_data = f.read()
						image_type = imghdr.what(f.name)
						image_name = f.name

					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_address, sender_pass)
						smtp.send_message(newMessage)

					url = "https://www.fast2sms.com/dev/bulkV2"
					print(url)

					no = '9390517887'
					data = {
						"route": "q",
						"message": mail_content1,
						"language": "english",
						"flash": 0,
						"numbers": no,
					}
					headers = {
						"authorization": "NgtD58YWLjubd2wXVFHAyrP6xOmRvaKeECJ1GhQUBfSsMc7piob3ELPkxpFqQnT7Gu6sitdUIBXMCrSW",
						"Content-Type": "application/json"
					}
					response = requests.post(url, headers=headers, json=data)
					print(response)
					cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36,255,12), 2)


		#Show the frames
	cv2.imshow("Frame", frame)
	count.append(det)
	#Alerts only if at least 15 frames sucessfully detects animals in the last 36 frames (appx 2 sec)

	#if flag==1 and len(count) > c+36:
	#	flag=0
	if flag==1 and len(count) > c +(11*18):
		flag=0
	if Counter(count[len(count)-36:])[1] > 15 and flag==0:


		c=len(count)

	key = cv2.waitKey(1)
	if key == ord("q"):
		break
	fps.update()

fps.stop()
print("Elapsed time: {:.2f}".format(fps.elapsed()))
print("Approximate FPS: {:.2f}".format(fps.fps()))
vs.release()
cv2.destroyAllWindows()
#vs.stop()



content_copyCOPY