<jupyter_start><jupyter_text><jupyter_code>import os
import pathlib


if "models" in pathlib.Path.cwd().parts:
  while "models" in pathlib.Path.cwd().parts:
    os.chdir('..')
elif not pathlib.Path('models').exists():
  !git clone --depth 1 https://github.com/tensorflow/models
!pip install tensorflow-object-detection-api
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import pathlib

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from IPython.display import display

from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# patch tf1 into `utils.ops`
utils_ops.tf = tf.compat.v1

# Patch the location of gfile
tf.gfile = tf.io.gfile
def load_model(model_name):
  base_url = 'http://download.tensorflow.org/models/object_detection/'
  model_file = model_name + '.tar.gz'
  model_dir = tf.keras.utils.get_file(
    fname=model_name, 
    origin=base_url + model_file,
    untar=True)

  model_dir = pathlib.Path(model_dir)/"saved_model"

  model = tf.saved_model.load(str(model_dir))
  model = model.signatures['serving_default']

  return model
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = '/content/models/research/object_detection/data/mscoco_label_map.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
model_name = 'ssd_mobilenet_v1_coco_2017_11_17'
detection_model = load_model(model_name)
def run_inference_for_single_image(model, image):
  image = np.asarray(image)
  # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
  input_tensor = tf.convert_to_tensor(image)
  # The model expects a batch of images, so add an axis with `tf.newaxis`.
  input_tensor = input_tensor[tf.newaxis,...]

  # Run inference
  output_dict = model(input_tensor)

  # All outputs are batches tensors.
  # Convert to numpy arrays, and take index [0] to remove the batch dimension.
  # We're only interested in the first num_detections.
  num_detections = int(output_dict.pop('num_detections'))
  output_dict = {key:value[0, :num_detections].numpy() 
                 for key,value in output_dict.items()}
  output_dict['num_detections'] = num_detections

  # detection_classes should be ints.
  output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)
   
  # Handle models with masks:
  if 'detection_masks' in output_dict:
    # Reframe the the bbox mask to the image size.
    detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
              output_dict['detection_masks'], output_dict['detection_boxes'],
               image.shape[0], image.shape[1])      
    detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,
                                       tf.uint8)
    output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()
    
  return output_dict
def show_inference(model, image_path):
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = image_path
  image_np=cv2.cvtColor(image_np,cv2.COLOR_BGR2RGB)
  # Actual detection.
  output_dict = run_inference_for_single_image(model, image_np)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks_reframed', None),
      use_normalized_coordinates=True,
      line_thickness=2)
  image_np=cv2.cvtColor(image_np,cv2.COLOR_BGR2RGB)
  person_detect(image_np,output_dict['detection_classes'],output_dict['detection_scores'],output_dict['detection_boxes'])
  return image_np
!mkdir /content/image_results_4rom_boxes
from datetime import datetime

def person_detect(image,classes,score,boxes):
    
    for i in range(10):
        if(classes[i]==1 and score[i]>0.8):
            
            h,w=image.shape[0:2]
            #image.shape=[height,width,3]
            
            ymin,xmin,ymax,xmax=boxes[i]

            now = datetime.now()
            dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
            
            center=(int(((xmin+xmax)/2)*w),int(((ymin+ymax)/2)*h))
            cv2.circle(image,center,10,(0,0,255),-1)
            
            file_name=os.path.join('/content/image_results_4rom_boxes',dt_string+'.jpg')
            cv2.imwrite(file_name,image)<jupyter_output><empty_output><jupyter_text>Building the database by scraping the video of each car type and save yolo detection result as car type for databaseWe are going to Make databases on the following YouTube video:<jupyter_code>!pip3 install youtube_dl 

#@title
import os
from os.path import exists, join, basename, splitext 
from IPython.display import YouTubeVideo

YOUTUBE_ID = 'xFLckB7vOQc' #(Ford Festiva)


YouTubeVideo(YOUTUBE_ID)
%cd '/content/'
# %cd '/content/drive/My Drive/Torrent/'
# !rm -rf *.wav
# !youtube-dl  --output "test.%(ext)s" https://www.youtube.com/watch\?v\={YOUTUBE_ID}
!youtube-dl --format "bestvideo+bestaudio[ext=m4a]/bestvideo+bestaudio/best" --merge-output-format mp4  --output "Ford_Festiva.%(ext)s" https://www.youtube.com/watch\?v\={YOUTUBE_ID}

# !deepspeech --model deepspeech-0.6.1-models/output_graph.pbmm --lm deepspeech-0.6.1-models/lm.binary --trie deepspeech-0.6.1-models/trie --audio test.wav   --extended --json 
!ls
# !ffmpeg Ford_Festiva.mp4 -t 60 -c copy Ford_Festiva2.mp4
!ffmpeg -i Ford_Festiva.mp4 -ss 00:00:03 -t 00:10:08 -async 1 Ford_Festiva2.mp4
!ls
import cv2
from google.colab.patches import cv2_imshow
video=cv2.VideoCapture('/content/Ford_Festiva2.mp4')

while(True):
    ret,img=video.read()
    img=show_inference(detection_model,img)
    cv2_imshow(img)
    k=cv2.waitKey(1)
    
    if(k==27):
        break
cv2.destroyAllWindows()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10709656513285806, 'fraction_numerical': 0.015392093324692158, 'mean_word_length': 4.152754590984975, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 3, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '246376', 'license': 'MIT', 'n_tokens_mistral': 2208, 'n_tokens_neox': 2116, 'n_words': 449, 'path': 'object_detection_for database_making_method2.ipynb', 'repo_name': 'CAR-Driving/yoloOnGoogleColab', 'size': '6172'}