sandeep03edu

test_camera working

Jun 19th, 2022
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.65 KB | None | 0 0
  1. """
  2. Run classification on Camera, Press ESC to exit the program
  3. For Raspberry PI, please use `import tflite_runtime.interpreter as tflite` instead
  4. """
  5. from tkinter.messagebox import NO
  6. from pygame.locals import *
  7. import pygame.camera
  8. import pygame
  9. import socket
  10. from datetime import datetime, date
  11. from multiprocessing import Process
  12. import threading
  13. import warnings
  14.  
  15. from openpyxl import Workbook
  16. import pyttsx3
  17. import io
  18. from PIL import Image
  19. from pymongo import MongoClient
  20. from pygame import mixer
  21. import pandas as pd
  22. import sys
  23. import time
  24. import numpy as np
  25. import tensorflow.lite as tflite
  26. from tensorflow.keras.preprocessing.image import img_to_array
  27. import tensorflow as tf  # version 1.14
  28. import cv2
  29. import os
  30. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  31. warnings.filterwarnings('ignore')
  32.  
  33.  
  34.  
  35. CAMERA_WIDTH = 640
  36. CAMERA_HEIGHT = 480
  37.  
  38.  
  39. def textToSpeech():
  40.     engine = pyttsx3.init()
  41.     voices = engine.getProperty("voices")
  42.     engine.setProperty("voice", voices[1].id)
  43.     engine.setProperty("rate", 220)
  44.     engine.say("Suspecious Activity Detected!")
  45.     engine.runAndWait()
  46.     del engine
  47.  
  48.  
  49. def alert():
  50.     t = threading.Thread(target=textToSpeech)
  51.     t.start()
  52.  
  53.  
  54. def load_labels(label_path):
  55.     r"""Returns a list of labels"""
  56.     with open(label_path, 'r') as f:
  57.         return [line.strip() for line in f.readlines()]
  58.  
  59.  
  60. def load_model(model_path):
  61.     r"""Load TFLite model, returns a Interpreter instance."""
  62.     interpreter = tflite.Interpreter(model_path=model_path)
  63.     interpreter.allocate_tensors()
  64.     return interpreter
  65.  
  66.  
  67. def process_image(interpreter, image, input_index, k=3):
  68.     r"""Process an image, Return top K result in a list of 2-Tuple(confidence_score, _id)"""
  69.     input_data = np.expand_dims(image, axis=0)  # expand to 4-dim
  70.  
  71.     # Process
  72.     interpreter.set_tensor(input_index, input_data)
  73.     interpreter.invoke()
  74.  
  75.     # Get outputs
  76.     output_details = interpreter.get_output_details()
  77.     output_data = interpreter.get_tensor(output_details[0]['index'])
  78.     output_data = np.squeeze(output_data)
  79.  
  80.     # Get top K result
  81.     top_k = output_data.argsort()[-k:][::-1]  # Top_k index
  82.     result = []
  83.     for _id in top_k:
  84.         score = float(output_data[_id] / 255.0)
  85.         result.append((_id, score))
  86.  
  87.     return result
  88.  
  89.  
  90. def display_result(top_result, frame, labels):
  91.     r"""Display top K result in top right corner"""
  92.     font = cv2.FONT_HERSHEY_SIMPLEX
  93.     size = 0.6
  94.     color = (255, 0, 0)  # Blue color
  95.     thickness = 1
  96.  
  97.     for idx, (_id, score) in enumerate(top_result):
  98.         x = 12
  99.         y = 24 * idx + 24
  100.         cv2.putText(frame, '{} - {:0.4f}'.format(labels[_id], score),
  101.                     (x, y), font, size, color, thickness)
  102.  
  103.     cv2.imshow('Image Classification', frame)
  104.  
  105.  
  106. if __name__ == "__main__":
  107.  
  108.     model_path = 'S:\Projects\ObsenceMediaDetector\ocd_module_deployment-realtime_final\scuffle_tm_quant.tflite'
  109.     model_path1 = 'S:\Projects\ObsenceMediaDetector\ocd_module_deployment-realtime_final\obscenetmquant.tflite'
  110.     label_path = 'S:\Projects\ObsenceMediaDetector\ocd_module_deployment-realtime_final\labels_scuffle.txt'
  111.     label_path1 = 'S:\Projects\ObsenceMediaDetector\ocd_module_deployment-realtime_final\labels_obscene.txt'
  112.  
  113.     cap = cv2.VideoCapture('S:\Projects\ObsenceMediaDetector\ocd_module_deployment-realtime_final\demo.mp4')
  114.     cap.set(cv2.CAP_PROP_FRAME_WIDTH, CAMERA_WIDTH)
  115.     cap.set(cv2.CAP_PROP_FRAME_HEIGHT, CAMERA_HEIGHT)
  116.     cap.set(cv2.CAP_PROP_FPS, 15)
  117.  
  118.     interpreter = load_model(model_path)
  119.     interpreter1 = load_model(model_path1)
  120.     labels = load_labels(label_path)
  121.     labels1 = load_labels(label_path1)
  122.  
  123.     input_details = interpreter.get_input_details()
  124.     input_details1 = interpreter1.get_input_details()
  125.  
  126.     # Get Width and Height
  127.     input_shape = input_details[0]['shape']
  128.     input_shape1 = input_details1[0]['shape']
  129.     height = input_shape[1]
  130.     height = input_shape1[1]
  131.     width = input_shape[2]
  132.     width = input_shape1[2]
  133.  
  134.     # Get input index
  135.     input_index = input_details[0]['index']
  136.     input_index1 = input_details1[0]['index']
  137.  
  138.     # Process Stream
  139.     while True:
  140.         ret, frame = cap.read()
  141.         image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
  142.         image = image.resize((width, height))
  143.  
  144.         top_result = process_image(interpreter, image, input_index)
  145.         top_result1 = process_image(interpreter1, image, input_index1)
  146.  
  147.         # folder
  148.         path = "./record"
  149.  
  150.         # Check whether the specified path exists or not
  151.         isExist = os.path.exists(path)
  152.         print(isExist)
  153.  
  154.         if not isExist:
  155.             os.makedirs(path)
  156.             print("new directory is created!")
  157.  
  158.         if isExist:
  159.             path_w = "./record/weapon"
  160.             isExist = os.path.exists(path_w)
  161.             print(isExist)
  162.  
  163.         if not isExist:
  164.             os.makedirs(path_w)
  165.             print("new directory is created!")
  166.  
  167.         path_v = "./record/vehicle"
  168.         isExist = os.path.exists(path_v)
  169.         print(isExist)
  170.  
  171.         if not isExist:
  172.             os.makedirs(path_v)
  173.             print("new directory is created!")
  174.  
  175.         path_f = "./record/face"
  176.         isExist = os.path.exists(path_f)
  177.         print(isExist)
  178.  
  179.         if not isExist:
  180.             os.makedirs(path_f)
  181.             print("new directory is created!")
  182.  
  183.         path_fb = "./record/fullbody"
  184.         isExist = os.path.exists(path_fb)
  185.         print(isExist)
  186.  
  187.         if not isExist:
  188.             os.makedirs(path_fb)
  189.             print("new directory is created!")
  190.  
  191.         path_scf = "./record/scfproof"
  192.         isExist = os.path.exists(path_scf)
  193.         print(isExist)
  194.  
  195.         if not isExist:
  196.             os.makedirs(path_scf)
  197.             print("new directory is created!")
  198.  
  199.         path_obs = "./record/obsproof"
  200.         isExist = os.path.exists(path_obs)
  201.         print(isExist)
  202.  
  203.         if not isExist:
  204.             os.makedirs(path_obs)
  205.             print("new directory is created!")
  206.  
  207.         import csv
  208.  
  209.         with open('./record/record.csv', 'wb') as csvfile:
  210.             filewriter = csv.writer(
  211.                 csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
  212.  
  213.         wb = Workbook("./record/record.xlsx")
  214.         wb.save("./record/record.xlsx")
  215.  
  216.         # Timing
  217.         now = datetime.now()
  218.         start_time = 10
  219.         t3 = now.strftime("%Hh%Mm%Ss")
  220.         today = date.today()
  221.         d3 = today.strftime("%B%d%Y")
  222.  
  223.         # client = MongoClient(
  224.         #     "mongodb://localhost:27017")
  225.         # db = client.edgedev
  226.         # obsproof = db.obsproof
  227.         # faceproof = db.faceproof
  228.         # vehicleproof = db.vehicleproof
  229.         # weaponproof = db.weaponproof
  230.         # fullbodyproof = db.fullbodyproof
  231.         # scfproof = db.scfproof
  232.         # wproof = db.wproof
  233.  
  234.         # Prediction mechanism obscene
  235.         string_pred_gen = ['NonObscene', 'Obscene']
  236.         interpreter_obs = load_model(model_path="obscenetmquant.tflite")
  237.         interpreter_obs = tflite.Interpreter(
  238.             model_path="obscenetmquant.tflite")
  239.         interpreter_obs.allocate_tensors()
  240.         input_details_obs = interpreter_obs.get_input_details()
  241.         output_details_obs = interpreter_obs.get_output_details()
  242.         input_shape_obs = input_details_obs[0]['shape']
  243.  
  244.         # Prediction mechanism scuffle
  245.         string_pred_gena = ['NoScuffle', 'Scuffle']
  246.         interpreter_scuf = load_model(model_path="scuffle_tm_quant.tflite")
  247.         interpreter_scuf = tflite.Interpreter(
  248.             model_path="scuffle_tm_quant.tflite")
  249.         interpreter_scuf.allocate_tensors()
  250.         input_details_scuf = interpreter_scuf.get_input_details()
  251.         output_details_scuf = interpreter_scuf.get_output_details()
  252.         input_shape_scuf = input_details_scuf[0]['shape']
  253.        
  254.         # Initializing variables
  255.         input_im = None
  256.         Time = []
  257.         Date = []
  258.         Act = []
  259.         count = 0
  260.         # colors = np.random.uniform(0, 255, size=(len(classes), 3))
  261.         act = "act"
  262.  
  263.         # reading the stream and resizing it from (320x240, 640x480, 1280x720, 1920x1080)
  264.         # "http://192.168.0.2:4747/video")#"dems.mp4"http://192.168.0.2:4747/video or 0,1,2
  265.         cap = cv2.VideoCapture('S:\Projects\ObsenceMediaDetector\ocd_module_deployment-realtime_final\demo.mp4')
  266.         cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
  267.         cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
  268.  
  269.         font = cv2.FONT_HERSHEY_TRIPLEX
  270.         if (cap.isOpened() == False):
  271.             # print("Error reading video file")
  272.             engine = pyttsx3.init()
  273.             engine.say(
  274.                 "Your CCTV camera is not working or turned off! Please check it and get back here!")
  275.             engine.runAndWait()
  276.             sys.exit()
  277.         frame_width = int(cap.get(3))
  278.         frame_height = int(cap.get(4))
  279.         size = (frame_width, frame_height)
  280.  
  281.         while True:
  282.             _, frame = cap.read()
  283.             input_im = frame
  284.             count = 0
  285.             start_time = 10
  286.             now = datetime.now()
  287.             d3 = today.strftime("%B %d, %Y")
  288.             t3 = now.strftime("%H:%M:%S")
  289.             cv2.putText(input_im, d3, (20, 400), font, 1,
  290.                         (250, 250, 250), 1, cv2.LINE_AA)
  291.             cv2.putText(input_im, t3, (20, 440), font, 1,
  292.                         (250, 250, 250), 1, cv2.LINE_AA)
  293.  
  294.             input_im = cv2.resize(input_im, (224, 224))
  295.             input_im = img_to_array(input_im)
  296.             input_im = np.expand_dims(input_im, axis=0)
  297.             height, width, channels = frame.shape
  298.            
  299.            
  300.             input_data = np.array(input_im)
  301.             input_data=input_data.astype(np.uint8)
  302.             interpreter_obs.set_tensor(
  303.                 input_details_obs[0]['index'], input_data)
  304.             interpreter_obs.invoke()
  305.             interpreter_scuf.set_tensor(
  306.                 input_details_scuf[0]['index'], input_data)
  307.             interpreter_scuf.invoke()
  308.             output_data_obs = interpreter_obs.get_tensor(
  309.                 output_details_obs[0]['index'])
  310.             index_pred_obs = 1 if (output_data_obs[0][1] > 0.5) else 0
  311.             output_data_scuf = interpreter_scuf.get_tensor(
  312.                 output_details_scuf[0]['index'])
  313.             ind = 1 if (output_data_scuf[0][1] > 0.75) else 0
  314.             prezic_obs = string_pred_gen[index_pred_obs]
  315.             prezic_scuf = string_pred_gena[ind]
  316.             d3 = today.strftime("%B%d%Y")
  317.             t3 = now.strftime("%Hh%Mm%Ss")
  318.  
  319.             if(prezic_obs == 'Obscene') and (prezic_scuf == 'Scuffle'):
  320.                 cv2.putText(frame, prezic_obs, (40, 50), font,
  321.                             2, (0, 0, 255), 5, cv2.LINE_AA)
  322.                 cv2.putText(frame, prezic_scuf, (40, 100), font,
  323.                             2, (0, 0, 255), 5, cv2.LINE_AA)
  324.                 alert()
  325.                 act = "Obscene and Scuffle"
  326.                 OSFileName = "record/obsProof/obs_" + \
  327.                     str(d3) + str(t3) + ".jpg"
  328.                 cv2.imwrite(OSFileName, frame)
  329.                 OSFileName = "record/scfProof/scf_" + \
  330.                     str(d3) + str(t3) + ".jpg"
  331.                 cv2.imwrite(OSFileName, frame)
  332.                 ima = Image.open(OSFileName)
  333.                 image_bytes = io.BytesIO()
  334.                 ima.save(image_bytes, format='JPEG')
  335.                 image = {
  336.                     'data': image_bytes.getvalue(),
  337.                     'Suspecious Activity': act,
  338.                     'date': d3,
  339.                     'time': t3
  340.                 }
  341.                 # obsproof.insert_one(image)
  342.                 # scfproof.insert_one(image)
  343.  
  344.             elif (prezic_obs == 'Obscene') and (prezic_scuf != 'Scuffle'):
  345.                 cv2.putText(frame, prezic_obs, (40, 50), font,
  346.                             2, (0, 0, 255), 5, cv2.LINE_AA)
  347.                 cv2.putText(frame, prezic_scuf, (40, 100), font,
  348.                             2, (255, 255, 255), 1, cv2.LINE_AA)
  349.                 alert()
  350.                 act = "Obscene"
  351.                 OFileName = "record/obsProof/obs_" + str(d3) + str(t3) + ".jpg"
  352.                 cv2.imwrite(OFileName, frame)
  353.                 ima = Image.open(OFileName)
  354.                 image_bytes = io.BytesIO()
  355.                 ima.save(image_bytes, format='JPEG')
  356.                 image = {
  357.                     'data': image_bytes.getvalue(),
  358.                     'Suspecious Activity': act,
  359.                     'date': d3,
  360.                     'time': t3
  361.                 }
  362.                 # obsproof.insert_one(image)
  363.  
  364.             elif (prezic_obs != 'Obscene') and (prezic_scuf == 'Scuffle'):
  365.                 cv2.putText(frame, prezic_obs, (40, 50), font,
  366.                             2, (255, 255, 255), 1, cv2.LINE_AA)
  367.                 cv2.putText(frame, prezic_scuf, (40, 100), font,
  368.                             2, (0, 0, 255), 5, cv2.LINE_AA)
  369.                 alert()
  370.                 act = "Scuffle"
  371.                 SFileName = "record/scfProof/scf_" + str(d3) + str(t3) + ".jpg"
  372.                 cv2.imwrite(SFileName, frame)
  373.                 ima = Image.open(SFileName)
  374.                 image_bytes = io.BytesIO()
  375.                 ima.save(image_bytes, format='JPEG')
  376.                 image = {
  377.                     'data': image_bytes.getvalue(),
  378.                     'Suspecious Activity': act,
  379.                     'date': d3,
  380.                     'time': t3
  381.                 }
  382.                 # scfproof.insert_one(image)
  383.  
  384.             else:
  385.                 cv2.putText(frame, prezic_obs, (20, 30), font,
  386.                             1, (255, 255, 255), 1, cv2.LINE_AA)
  387.                 cv2.putText(frame, prezic_scuf, (20, 60), font,
  388.                             1, (255, 255, 255), 1, cv2.LINE_AA)
  389.  
  390.                
  391.             # or (indexes == 0):
  392.             if(prezic_obs == 'Obscene') or (prezic_scuf == 'Scuffle'):
  393.                 Time.append(t3)
  394.                 Date.append(d3)
  395.                 Act.append(act)
  396.                 dict = {'Time': Time, 'Date': Date, 'Activity': Act}
  397.                 df = pd.DataFrame(dict)
  398.                 df.to_csv('record/record.csv')
  399.                 df.to_excel('record/recording.xlsx')
  400.                 detector = cv2.CascadeClassifier(
  401.                     'haarcascade_frontalface_default.xml')
  402.                 faces = detector.detectMultiScale(frame, 1.3, 5, 0)
  403.                 for (ex, ey, ew, eh) in faces:
  404.                     roi_color = frame[ey:ey+eh, ex:ex+ew]
  405.                     cv2.rectangle(frame, (ex, ey),
  406.                                     (ex+ew, ey+eh), (0, 255, 0), 2)
  407.                     FFileName = "record/face/faces_" + \
  408.                         str(d3) + str(t3) + ".jpg"
  409.                     cv2.imwrite(FFileName, roi_color)
  410.                     ima = Image.open(FFileName)
  411.                     image_bytes = io.BytesIO()
  412.                     ima.save(image_bytes, format='JPEG')
  413.                     image = {
  414.                         'data': image_bytes.getvalue(),
  415.                         'Suspecious Activity': act,
  416.                         'date': d3,
  417.                         'time': t3
  418.                     }
  419.                     # faceproof.insert_one(image)
  420.  
  421.                 # weapon
  422.                 w_detector = cv2.CascadeClassifier('gun_cascade.xml')
  423.                 weapons = detector.detectMultiScale(frame, 1.3, 5, 0)
  424.                 for (ex, ey, ew, eh) in weapons:
  425.                     roi_color = frame[ey:ey+eh, ex:ex+ew]
  426.                     cv2.rectangle(frame, (ex, ey),
  427.                                     (ex+ew, ey+eh), (0, 255, 0), 2)
  428.                     WFileName = "./record/weapon/weapons_" + \
  429.                         str(d3) + str(t3) + ".jpg"
  430.                     cv2.imwrite(WFileName, roi_color)
  431.                     ima = Image.open(WFileName)
  432.                     image_bytes = io.BytesIO()
  433.                     ima.save(image_bytes, format='JPEG')
  434.                     image = {
  435.                         'data': image_bytes.getvalue(),
  436.                         'Suspecious Activity': act,
  437.                         'date': d3,
  438.                         'time': t3
  439.                     }
  440.                     # weaponproof.insert_one(image)
  441.  
  442.                 # vehicle
  443.                 v_detector = cv2.CascadeClassifier('cascade.xml')
  444.                 vehicles = detector.detectMultiScale(frame, 1.3, 5, 0)
  445.                 for (ex, ey, ew, eh) in vehicles:
  446.                     roi_color = frame[ey:ey+eh, ex:ex+ew]
  447.                     cv2.rectangle(frame, (ex, ey),
  448.                                     (ex+ew, ey+eh), (0, 255, 0), 2)
  449.                     VFileName = "./record/vehicle/vehicles_" + \
  450.                         str(d3) + str(t3) + ".jpg"
  451.                     cv2.imwrite(VFileName, roi_color)
  452.                     ima = Image.open(VFileName)
  453.                     image_bytes = io.BytesIO()
  454.                     ima.save(image_bytes, format='JPEG')
  455.                     image = {
  456.                         'data': image_bytes.getvalue(),
  457.                         'Suspecious Activity': act,
  458.                         'date': d3,
  459.                         'time': t3
  460.                     }
  461.                     # vehicleproof.insert_one(image)
  462.  
  463.                 #    full body
  464.                 fb_detector = cv2.CascadeClassifier('haarcascade_fullbody.xml')
  465.                 fullbody = detector.detectMultiScale(frame, 1.3, 5, 0)
  466.                 for (ex, ey, ew, eh) in fullbody:
  467.                     roi_color = frame[ey:ey+eh, ex:ex+ew]
  468.                     cv2.rectangle(frame, (ex, ey),
  469.                                     (ex+ew, ey+eh), (0, 255, 0), 2)
  470.                     FBFileName = "./record/fullbody/fullbody_" + \
  471.                         str(d3) + str(t3) + ".jpg"
  472.                     cv2.imwrite(FBFileName, roi_color)
  473.                     ima = Image.open(FBFileName)
  474.                     image_bytes = io.BytesIO()
  475.                     ima.save(image_bytes, format='JPEG')
  476.                     image = {
  477.                         'data': image_bytes.getvalue(),
  478.                         'Suspecious Activity': act,
  479.                         'date': d3,
  480.                         'time': t3
  481.                     }
  482.                     # fullbodyproof.insert_one(image)
  483.  
  484.                 # face
  485.                 face_detector = cv2.CascadeClassifier(
  486.                     'haarcascade_frontalface_default.xml')
  487.                 face = detector.detectMultiScale(frame, 1.3, 5, 0)
  488.                 for (ex, ey, ew, eh) in face:
  489.                     roi_color = frame[ey:ey+eh, ex:ex+ew]
  490.                     cv2.rectangle(frame, (ex, ey),
  491.                                     (ex+ew, ey+eh), (0, 255, 0), 2)
  492.                     FCFileName = "./record/face/face_" + \
  493.                         str(d3) + str(t3) + ".jpg"
  494.                     cv2.imwrite(FCFileName, roi_color)
  495.                     ima = Image.open(FCFileName)
  496.                     image_bytes = io.BytesIO()
  497.                     ima.save(image_bytes, format='JPEG')
  498.                     image = {
  499.                         'data': image_bytes.getvalue(),
  500.                         'Suspecious Activity': act,
  501.                         'date': d3,
  502.                         'time': t3
  503.                     }
  504.                     # faceproof.insert_one(image)
  505.  
  506.             # cv2.imshow("Live Streaming", frame)
  507.             key = cv2.waitKey(1)
  508.             if key == ord('q') or key == ord('Q'):
  509.                 cap.release()
  510.                 cv2.destroyAllWindows()
  511.                 break
  512.  
  513.             display_result(top_result, frame, labels)
  514.             display_result(top_result1, frame, labels)
  515.  
  516.         key = cv2.waitKey(1)
  517.         if key == 27:  # esc
  518.             break
  519.  
  520.         cap.release()
  521.         cv2.destroyAllWindows()
  522.  
Advertisement
Add Comment
Please, Sign In to add comment