<jupyter_start><jupyter_text>Imports<jupyter_code>import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
# import Image

# if tf.__version__ < '1.4.0':
#     raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')<jupyter_output><empty_output><jupyter_text>Env setup<jupyter_code># This is needed to display the images.
%matplotlib inline

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")<jupyter_output><empty_output><jupyter_text>Object detection importsHere are the imports from the object detection module.<jupyter_code>from utils import label_map_util

from utils import visualization_utils as vis_util<jupyter_output><empty_output><jupyter_text>Model preparation   VariablesAny model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file.  By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.  Download Model<jupyter_code># opener = urllib.request.URLopener()
# print(1)
# opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
# print(1)
# MODEL_NAME = 'faster_rcnn_resnet101_kitti_2017_11_08'
# MODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_lowproposals_oid_2017_11_08'
# MODEL_NAME = 'ssd_inception_v2_coco_2017_11_17 (1)'
# MODEL_NAME = 'facessd_mobilenet_v2_quantized_320x320_open_image_v4'
# MODEL_NAME = 'faster_rcnn_resnet101_ava_v2.1_2018_04_30'
# MODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_lowproposals_oid_2018_01_28'
# MODEL_NAME = 'inception_v4_2016_09_09'
# MODEL_NAME = 'mobilenet_v1_0.25_128_quant'
MODEL_NAME = 'mask_rcnn_resnet50_atrous_coco_2018_01_28'

# MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
# MODEL_NAME = 'rfcn_resnet101_coco_2017_11_08'

MODEL_FILE = MODEL_NAME + '.tar.gz'
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
# PATH_TO_CKPT = 'inception_v4.ckpt'
# PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map_modified_FOOD.pbtxt')
NUM_CLASSES = 90
tar_file = tarfile.open(MODEL_FILE)
print(1)
for file in tar_file.getmembers():
    file_name = os.path.basename(file.name)
    if 'frozen_inference_graph.pb' in file_name:
#     if 'inception_v4.ckpt' in file_name:
        tar_file.extract(file, os.getcwd())<jupyter_output>1<jupyter_text>Load a (frozen) Tensorflow model into memory.<jupyter_code>detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')<jupyter_output><empty_output><jupyter_text>Loading label mapLabel maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine<jupyter_code>label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
namelist=[]
indexlist=[]
for i in category_index.values():
    namelist.append(i['name'])
    indexlist.append(i['id'])
#importing modules
import cv2
import numpy as np
import math
import time
import _thread
import wave
import struct

def playSound(name):
    import simpleaudio as sa

    wave_obj = sa.WaveObject.from_wave_file('./Sounds/'+name)
    play_obj = wave_obj.play()


#     ####CRASHES ON FAST INPUT####
#     import pyglet
#     player = pyglet.media.Player()
#     src = pyglet.media.load(name)
#     player.volume = 0.1
#     player.queue(src)
#     player.play()

#     ####VERY SLOW####
#     import pygame.mixer
#     pm = pygame.mixer
#     pm.init()
#     sound = pm.Sound(name)
#     sound.set_volume(0.5)
#     sound.play()



def drawEllipse(contours, text):
    if(contours == None or len(contours) == 0):
        return ((-100,-100), None)
    c = max(contours, key=cv2.contourArea)
    ((x, y), radius) = cv2.minEnclosingCircle(c)
    if(cv2.contourArea(c) < 500):
        return ((-100,-100), None)
    ellipse = cv2.fitEllipse(c)
    cv2.ellipse(image_np, ellipse, (0,0,0), 2)

    blank = np.zeros(image_np.shape[0:2])
    ellipseImage = cv2.ellipse(blank, ellipse, (255, 255, 255), -2)
    # cv2.imshow("ell",ellipseImage)

    M = cv2.moments(c)
    if M["m00"] == 0:
        return
    center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

    if radius > 10:
        # draw the ellipse and centroid on the frame,
        # then update the list of tracked points
        # cv2.circle(img, (int(x), int(y)), int(radius),(0, 0, 0), 2)
        cv2.circle(image_np, center, 3, (0, 0, 255), -1)
        cv2.putText(image_np,text, (center[0]+10,center[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.4,(0, 0, 0),2)
        cv2.putText(image_np,"("+str(center[0])+","+str(center[1])+")", (center[0]+10,center[1]+15), cv2.FONT_HERSHEY_SIMPLEX, 0.4,(0, 0, 0),1)

    return (center, ellipseImage)

def detectCollision(imgA, imgB, velocity, touching, name):
    mA = cv2.moments(imgA, False)
    mB = cv2.moments(imgB, False)
    blank = np.zeros(image_np.shape[0:2])
    if type(imgA) == type(None) or type(imgB) == type(None):
        return
    intersection = cv2.bitwise_and(imgA, imgB)
    area = cv2.countNonZero(intersection)
    if area < 20:
        touching = False
    if area > 100 and not touching:
        # print(int(mA["m01"] / mA["m00"])< int(mB["m01"] / mB["m00"]))
        # print(area)
        if int(mA["m01"] / mA["m00"])< int(mB["m01"] / mB["m00"]):
            if velocity > 0: # default is 10; this is the score that decides whether snare will be hit or not
                _thread.start_new_thread(playSound, (name,))
                # playSound(name)
        touching = True
    return touching

def newDrum(pos, name):
    # pos = (x, y)
    drum = cv2.circle(image_np,pos, 50,(0,0, 0),5)
    cv2.putText(drum,name,pos,cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
    blank = np.zeros(image_np.shape[0:2])
    drum_image = cv2.circle(blank.copy(), pos, 50, (255, 255, 255), -5)
    global numDrums
    numDrums += 1
    return (name, drum_image)
# music note repository
notes = [
'A3vH',
'A4vH',
'A5vH',
'A6vH',
'A7vH',
'B1vH',
'B2vH',
'B7vH',
'C1vH',
'C4vH',
'C5vH',
'C6vH',
'C7vH',
'D#2vH',
'D#3vH',
'D#4vH',
'D#5vH',
'D#6vH',
'D#7vH',
'F#1vH',
'F#2vH',
'F#3vH',
'F#4vH',
'F#5vH',
'F#6vH',
'F#7vH']
import os
path = './Guitar sounds'
os.listdir(path)<jupyter_output><empty_output><jupyter_text>Random Song Generation<jupyter_code># import random
# import cv2
# cap=cv2.VideoCapture(1) # 0 stands for very first webcam attach
# # https://www.youtube.com/watch?v=BUrR6BTx6Mk
# filename="outputtest.avi"#[place were i stored my output file]
# codec=cv2.VideoWriter_fourcc('m','p','4','v')#fourcc stands for four character code
# framerate=30
# resolution=(640,480)
# # resolution=(1080,640)

# frameCount = 0
# timeStart = time.time()

# b1 = (0,0)
# b2 = (0,0)
# currentBlueVelocity = 0
# r1 = (0,0)
# r2 = (0,0)
# currentRedVelocity = 0

# blueAndSnare = False
# blueAndHiHat = False
# redAndSnare = False
# redAndHiHat = False
# # booli  = [False for i in range(2)]
# booli  = [False for i in range(1)]

# numDrums = 0
# # drums = [None for i in range(2)]
# drums = [None for i in range(1)]

# item_lost = True
# # item_lost = False
# counter=0   
# tmarker=0
# VideoFileOutput=cv2.VideoWriter(filename,codec,framerate, resolution)
    
# with detection_graph.as_default():
#     with tf.Session(graph=detection_graph) as sess:
#         ret=True
#         while (ret):
            
#             ret, image_np=cap.read() 

#             f = open('output.txt', 'r')
#             x = [x.replace("\n", "") for x in f.readlines()][-1]
#             for i in range(len(namelist)):
#                 if namelist[i] in x:
#     #                 print(content[i], i)
#                     tmarker=indexlist[i]
#     #         print(tmarker)

#             if tmarker != -1:
#                 item_lost = True
#             if "found" in x:
#                 tmarker=-1
                
                
#             now = time.time()
#             fps = frameCount / (now - timeStart+1.0)
#             frameCount += 1

# #             _, img = cap.read()
# #             image_np = cv2.flip(image_np, 1)


            

#             # Definite input and output Tensors for detection_graph
#             image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
#             # Each box represents a part of the image where a particular object was detected.
#             detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
#             # Each score represent how level of confidence for each of the objects.
#             # Score is shown on the result image, together with the class label.
#             detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
#             detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
#             num_detections = detection_graph.get_tensor_by_name('num_detections:0')

#               # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
#             image_np_expanded = np.expand_dims(image_np, axis=0)
#               # Actual detection.
#             (boxes, scores, classes, num) = sess.run(
#                   [detection_boxes, detection_scores, detection_classes, num_detections],
#                   feed_dict={image_tensor: image_np_expanded})
#               # Visualization of the results of a detection.
#             if item_lost:
#                 image_np = vis_util.lost_item_mode(image_np,
#                   np.squeeze(boxes),
#                   np.squeeze(classes).astype(np.int32),
#                   np.squeeze(scores),
#                   category_index,
#                   use_normalized_coordinates=True,
#                   line_thickness=8,
#                   marker=tmarker)
# #                 cv2.imwrite(r'C:/Users/user/Desktop/Moverio-MemoryPalace-Instructions/Calhacks-5.0/Object-Detection-On-Live-Video-Feed/models/object_detection/data_images/img_'+str(counter)+'.jpg', image_np)
#                 counter+=1
#             else:
#                 image_np = vis_util.visualize_boxes_and_labels_on_image_array(
#                   image_np,
#                   np.squeeze(boxes),
#                   np.squeeze(classes).astype(np.int32),
#                   np.squeeze(scores),
#                   category_index,
#                   use_normalized_coordinates=True,
#                   line_thickness=8)
# #                 cv2.imwrite(r'C:/Users/user/Desktop/Moverio-MemoryPalace-Instructions/Calhacks-5.0/Object-Detection-On-Live-Video-Feed/models/object_detection/data_images/img_'+str(counter)+'.jpg', image_np)
#                 counter+=1
    
#             # cv2.putText(img,"FPS : ",(10,100),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,0), 2)
#             cv2.putText(image_np,"FPS: %.2f" % (fps),(10,100),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,0), 2)

#             # Add the drums
# #             drums[0] = newDrum((350, 400), "snare")
# #             drums[1] = newDrum((100, 400), "hi_hat")
# #             drums[0] = newDrum((800, 400), "snare (stick 1)")
# #             drums[1] = newDrum((300, 400), "hi_hat (stick 2)")
#             rand1 = random.randint(0,len(notes)-1)
#             rand2 = random.randint(0,len(notes)-1)
#             drums[0] = newDrum((400, 400), notes[rand1])
# #             drums[1] = newDrum((100, 400), notes[rand2])

#             #converting frame(img i.e BGR) to HSV (hue-saturation-value)
#             hsv=cv2.cvtColor(image_np,cv2.COLOR_BGR2HSV)

#             #defining the range of red color
# #             red_lower=np.array([255,255,255],np.uint8)
# #             red_upper=np.array([255,255,255],np.uint8)
#             red_lower=np.array([0,0,255],np.uint8)
#             red_upper=np.array([255,255,255],np.uint8)

#             #defining the Range of Blue color
#             blue_lower=np.array([0,0,255],np.uint8)
#             blue_upper=np.array([255,255,255],np.uint8)

#             #finding the range of red,blue color in the image
#             red=cv2.inRange(hsv, red_lower, red_upper)
#             blue=cv2.inRange(hsv,blue_lower,blue_upper)

#             #Morphological transformation, Dilation
#             kernal = np.ones((5 ,5), "uint8")

#             red=cv2.dilate(red, kernal)
#             res=cv2.bitwise_and(image_np, image_np, mask = red)

#             blue=cv2.dilate(blue,kernal)
#             res1=cv2.bitwise_and(image_np, image_np, mask = blue)


#             #Tracking the Red Color
#             (contours,hierarchy)=cv2.findContours(red,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#             (redCenter, redEllipse) = drawEllipse(contours, "Red")
# #             cv2.drawContours(image_np, contours, -1 , (0,0,255), 2)


#             #Tracking the Blue Color
#             (contours,hierarchy)=cv2.findContours(blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# #             cv2.drawContours(image_np, contours, -1 , (255,0,0), 2)
#             (blueCenter, blueEllipse) = drawEllipse(contours, "Blue")

#             b1 = b2
#             b2 = blueCenter
#             bDelta = math.sqrt((b2[0] - b1[0])**2 + (b2[1] - b1[1])**2)
#             bVelocity = bDelta * fps / 100
#             if (bVelocity - currentBlueVelocity) > 10:
#                 cv2.putText(image_np,str(int(bVelocity)),(10, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0), 2)
#             else:
#                 cv2.putText(image_np,str(int(currentBlueVelocity)),(10, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0), 2)
#             currentBlueVelocity = bVelocity

#             r1 = r2
#             r2 = redCenter
#             rDelta = math.sqrt((r2[0] - r1[0])**2 + (r2[1] - r1[1])**2)
#             rVelocity = rDelta * fps / 100
#             if (rVelocity - currentRedVelocity) > 10:
#                 cv2.putText(image_np,str(int(rVelocity)),(70, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
#             else:
#                 cv2.putText(image_np,str(int(currentRedVelocity)),(70, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
#             currentRedVelocity = rVelocity


#             for i in range(len(drums)):
#                 # print(booli)
#                 booli[i] = detectCollision(blueEllipse, drums[i][1], currentBlueVelocity, booli[i], "{0}.wav".format(drums[i][0]))
#             ### comment out
# #             blueAndSnare = detectCollision(blueEllipse, drums[0][1], blueAndSnare, "snare.wav")
# #             blueAndHiHat = detectCollision(blueEllipse, drums[1][1], blueAndHiHat, "hi_hat.wav")

# #             blueAndSnare = detectCollision(blueEllipse, snare_image, blueAndSnare, "snare.wav")
# #             blueAndHiHat = detectCollision(blueEllipse, hi_hat_image, blueAndHiHat, "Closed-Hi-Hat.wav")
            
# #             redAndSnare = detectCollision(redEllipse, snare_image, redAndSnare, "snare.wav")
# #             redAndHiHat = detectCollision(redEllipse, hi_hat_image, redAndHiHat, "Closed-Hi-Hat.wav")
#             ###


#             #cv2.imshow("Redcolour",red)
# #             cv2.imshow("Color Tracking",img)
# #             #cv2.imshow("red",res)
# #             if cv2.waitKey(10) & 0xFF == ord('q'):
# #                 cap.release()
# #                 cv2.destroyAllWindows()
# #                 break    

#             VideoFileOutput.write(image_np)
#             cv2.imshow("Redcolour",red)
#             cv2.imshow('live_detection',image_np)
#             cv2.imshow("red",res)
#             if cv2.waitKey(25) & 0xFF==ord('q'):
#                 break
#                 cv2.destroyAllWindows()
#                 cap.release()<jupyter_output><empty_output><jupyter_text>Canon in D Major<jupyter_code>guitarChords = [
['C2','E3', 'G3', 'C3', 'E4'],
['F2','A2','D2','A3','D3'],
['E2','B2','E3','G3','B3'],
['F2','A2','E3','G3','B3'],    
['G2','B2','D2','G3','B3'],    
['A2','E3','A3','C3','E4'],
['G2','B2','D2','G3','B3'],
['C2','E3','G3','C3','E4']
]

# ｃ2　ｅ3　ｇ3　ｃ3　ｅ4
# ｇ2　ｂ2　ｄ2　ｇ3　ｂ3　
# ａ2　ｅ3　ａ3　ｃ3　ｅ4
# ｅ2　ｂ2　ｅ3　ｇ3　ｂ3　　
# ｆ2　ａ2　ｄ2　ａ3　ｄ3　
# ｃ2　ｅ3　ｇ3　ｃ3　ｅ4
# ｆ2　ａ2　ｆ3　ａ3　ｃ3　
# ｇ2　ｂ2　ｄ2　ｇ3　ｂ3

import random
import cv2
cap=cv2.VideoCapture(1) # 0 stands for very first webcam attach
# https://www.youtube.com/watch?v=BUrR6BTx6Mk
filename="outputtest.avi"#[place were i stored my output file]
codec=cv2.VideoWriter_fourcc('m','p','4','v')#fourcc stands for four character code
framerate=30
resolution=(640,480)
# resolution=(1080,640)

frameCount = 0
timeStart = time.time()

b1 = (0,0)
b2 = (0,0)
currentBlueVelocity = 0
r1 = (0,0)
r2 = (0,0)
currentRedVelocity = 0

blueAndSnare = False
blueAndHiHat = False
redAndSnare = False
redAndHiHat = False
# booli  = [False for i in range(2)]
booli  = [False for i in range(2+2+len(guitarChords[0]))]

numDrums = 0
# drums = [None for i in range(2)]
drums = [None for i in range(2+2+len(guitarChords[0]))]

item_lost = True
# item_lost = False
counter=0   
tmarker=0
VideoFileOutput=cv2.VideoWriter(filename,codec,framerate, resolution)
    
chordCounter = 0
    
with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        ret=True
        while (ret):
            
            ret, image_np=cap.read() 

            f = open('output.txt', 'r')
            x = [x.replace("\n", "") for x in f.readlines()][-1]
            for i in range(len(namelist)):
                if namelist[i] in x:
    #                 print(content[i], i)
                    tmarker=indexlist[i]
    #         print(tmarker)

            if tmarker != -1:
                item_lost = True
            if "found" in x:
                tmarker=-1
                
                
            now = time.time()
            fps = frameCount / (now - timeStart+1.0)
            frameCount += 1

#             _, img = cap.read()
#             image_np = cv2.flip(image_np, 1)


            

            # Definite input and output Tensors for detection_graph
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
            # Each box represents a part of the image where a particular object was detected.
            detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
            # Each score represent how level of confidence for each of the objects.
            # Score is shown on the result image, together with the class label.
            detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
            detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')

              # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
            image_np_expanded = np.expand_dims(image_np, axis=0)
              # Actual detection.
            (boxes, scores, classes, num) = sess.run(
                  [detection_boxes, detection_scores, detection_classes, num_detections],
                  feed_dict={image_tensor: image_np_expanded})
              # Visualization of the results of a detection.
            if item_lost:
                image_np = vis_util.lost_item_mode(image_np,
                  np.squeeze(boxes),
                  np.squeeze(classes).astype(np.int32),
                  np.squeeze(scores),
                  category_index,
                  use_normalized_coordinates=True,
                  line_thickness=8,
                  marker=tmarker)
#                 cv2.imwrite(r'C:/Users/user/Desktop/Moverio-MemoryPalace-Instructions/Calhacks-5.0/Object-Detection-On-Live-Video-Feed/models/object_detection/data_images/img_'+str(counter)+'.jpg', image_np)
                counter+=1
            else:
                image_np = vis_util.visualize_boxes_and_labels_on_image_array(
                  image_np,
                  np.squeeze(boxes),
                  np.squeeze(classes).astype(np.int32),
                  np.squeeze(scores),
                  category_index,
                  use_normalized_coordinates=True,
                  line_thickness=8)
#                 cv2.imwrite(r'C:/Users/user/Desktop/Moverio-MemoryPalace-Instructions/Calhacks-5.0/Object-Detection-On-Live-Video-Feed/models/object_detection/data_images/img_'+str(counter)+'.jpg', image_np)
                counter+=1
    
            # cv2.putText(img,"FPS : ",(10,100),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,0), 2)
            cv2.putText(image_np,"FPS: %.2f" % (fps),(10,100),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,0), 2)

            # Add the drums
            
#             drums[0] = newDrum((800, 400), "snare (stick 1)")
#             drums[1] = newDrum((300, 400), "hi_hat (stick 2)")

            chords = guitarChords[chordCounter]
            base = 350
            drums[0] = newDrum((base, base), chords[0])
            drums[1] = newDrum((base+25, base), chords[1])
            drums[2] = newDrum((base+50, base), chords[2])
            drums[3] = newDrum((base-25, base), chords[3])
            drums[4] = newDrum((base-50, base), chords[4])
            chordCounter += 1
            if chordCounter == 5:
                chordCounter=0
                
            drums[5] = newDrum((0, 50), "snare")
            drums[6] = newDrum((0, 100), "hi_hat")

            rand1 = random.randint(0,len(notes)-1)
            rand2 = random.randint(0,len(notes)-1)
            drums[7] = newDrum((0, 400), notes[rand1])
            drums[8] = newDrum((0, 300), notes[rand2])

            #converting frame(img i.e BGR) to HSV (hue-saturation-value)
            hsv=cv2.cvtColor(image_np,cv2.COLOR_BGR2HSV)

            #defining the range of red color
#             red_lower=np.array([255,255,255],np.uint8)
#             red_upper=np.array([255,255,255],np.uint8)
            red_lower=np.array([0,0,255],np.uint8)
            red_upper=np.array([255,255,255],np.uint8)

            #defining the Range of Blue color
            blue_lower=np.array([0,0,255],np.uint8)
            blue_upper=np.array([255,255,255],np.uint8)

            #finding the range of red,blue color in the image
            red=cv2.inRange(hsv, red_lower, red_upper)
            blue=cv2.inRange(hsv,blue_lower,blue_upper)

            #Morphological transformation, Dilation
            kernal = np.ones((5 ,5), "uint8")

            red=cv2.dilate(red, kernal)
            res=cv2.bitwise_and(image_np, image_np, mask = red)

            blue=cv2.dilate(blue,kernal)
            res1=cv2.bitwise_and(image_np, image_np, mask = blue)


            #Tracking the Red Color
            (contours,hierarchy)=cv2.findContours(red,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
            (redCenter, redEllipse) = drawEllipse(contours, "Red")
#             cv2.drawContours(image_np, contours, -1 , (0,0,255), 2)


            #Tracking the Blue Color
            (contours,hierarchy)=cv2.findContours(blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#             cv2.drawContours(image_np, contours, -1 , (255,0,0), 2)
            (blueCenter, blueEllipse) = drawEllipse(contours, "Blue")

            b1 = b2
            b2 = blueCenter
            bDelta = math.sqrt((b2[0] - b1[0])**2 + (b2[1] - b1[1])**2)
            bVelocity = bDelta * fps / 100
            if (bVelocity - currentBlueVelocity) > 10:
                cv2.putText(image_np,str(int(bVelocity)),(10, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0), 2)
            else:
                cv2.putText(image_np,str(int(currentBlueVelocity)),(10, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0), 2)
            currentBlueVelocity = bVelocity

            r1 = r2
            r2 = redCenter
            rDelta = math.sqrt((r2[0] - r1[0])**2 + (r2[1] - r1[1])**2)
            rVelocity = rDelta * fps / 100
            if (rVelocity - currentRedVelocity) > 10:
                cv2.putText(image_np,str(int(rVelocity)),(70, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
            else:
                cv2.putText(image_np,str(int(currentRedVelocity)),(70, 50),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
            currentRedVelocity = rVelocity


            for i in range(len(drums)):
                # print(booli)
                booli[i] = detectCollision(blueEllipse, drums[i][1], currentBlueVelocity, booli[i], "{0}.wav".format(drums[i][0]))
            ### comment out
#             blueAndSnare = detectCollision(blueEllipse, drums[0][1], blueAndSnare, "snare.wav")
#             blueAndHiHat = detectCollision(blueEllipse, drums[1][1], blueAndHiHat, "hi_hat.wav")

#             blueAndSnare = detectCollision(blueEllipse, snare_image, blueAndSnare, "snare.wav")
#             blueAndHiHat = detectCollision(blueEllipse, hi_hat_image, blueAndHiHat, "Closed-Hi-Hat.wav")
            
#             redAndSnare = detectCollision(redEllipse, snare_image, redAndSnare, "snare.wav")
#             redAndHiHat = detectCollision(redEllipse, hi_hat_image, redAndHiHat, "Closed-Hi-Hat.wav")
            ###


            #cv2.imshow("Redcolour",red)
#             cv2.imshow("Color Tracking",img)
#             #cv2.imshow("red",res)
#             if cv2.waitKey(10) & 0xFF == ord('q'):
#                 cap.release()
#                 cv2.destroyAllWindows()
#                 break    

            VideoFileOutput.write(image_np)
            cv2.imshow("Redcolour",red)
            cv2.imshow('live_detection',image_np)
            cv2.imshow("red",res)
            if cv2.waitKey(25) & 0xFF==ord('q'):
                break
                cv2.destroyAllWindows()
                cap.release()
# sound source: http://freepats.zenvoid.org/Guitar/steel-acoustic-guitar.html
# Canon in D Major demo: https://www.youtube.com/watch?v=Kvig-EYYM3w
# chords (Canon in D Major)
# ｃ2　ｅ3　ｇ3　ｃ3　ｅ4
# ｇ2　ｂ2　ｄ2　ｇ3　ｂ3　
# ａ2　ｅ3　ａ3　ｃ3　ｅ4
# ｅ2　ｂ2　ｅ3　ｇ3　ｂ3　　
# ｆ2　ａ2　ｄ2　ａ3　ｄ3　
# ｃ2　ｅ3　ｇ3　ｃ3　ｅ4
# ｆ2　ａ2　ｆ3　ａ3　ｃ3　
# ｇ2　ｂ2　ｄ2　ｇ3　ｂ3<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13512599992488827, 'fraction_numerical': 0.04371502610132572, 'mean_word_length': 2.5546655987184623, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 39, 'https://': 4, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '339247', 'license': 'MIT', 'n_tokens_mistral': 10470, 'n_tokens_neox': 9684, 'n_words': 1760, 'path': 'CVMusicSynthesis/objectdetection+airdrums-ver2.ipynb', 'repo_name': 'dattasiddhartha/HackUST2019', 'size': '26627'}