Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import time
- import cv2
- from pygame import mixer
- from shapely.geometry import Polygon
- verbose = False
- drumFile='sounds/snaredrum.wav'
- cymbalFile='sounds/ridecymbal.ogg'
- #La funcion playInstrument reproduce el sonido indicado
- def playInstrument(sound):
- #En función de en que region de interes se ha activado la funcion
- #se reproduce el sonido adecuado
- if sound==1:
- drum_clap.play()
- elif sound==2:
- drum_snare.play()
- time.sleep(0.001)
- #La funcion ROICheck ya no tiene que comprobar la existencia de un color
- #si no si las BBox de la ROI y del objeto trackeado se superponen
- #lo que significaría que se debe activar el sonido
- def ROIcheck(eq1, eq2, bbox ,sound):
- boxA = [eq1[0], eq2[1], eq2[0]-eq1[0], eq2[1]-eq1[1]]
- boxB = [bbox[0], bbox[1]+bbox[3], bbox[2], bbox[3]]
- poly_1 = Polygon([[eq1[0], eq2[1]], [eq2[0], eq2[1]], [eq2[0], eq1[1]], [eq1[0], eq1[1]]])
- poly_2 = Polygon([ [bbox[0], bbox[1]+bbox[3]], [bbox[0]+bbox[2], bbox[1]+bbox[3]], [bbox[0]+bbox[2], bbox[1]], [bbox[0], bbox[1]] ])
- print(poly_1.intersection(poly_2).area)
- if poly_1.intersection(poly_2).area > 0:
- playInstrument(sound)
- return True
- if __name__ == '__main__' :
- #El código comienza inicializando unas funciones del paquete pygame,
- #necesario para reproducir los sonidos de los instrumentos
- mixer.init()
- drum_clap = mixer.Sound(drumFile)
- drum_snare = mixer.Sound(cymbalFile)
- #Posteriormente, se inicia la lectura de video de openCV
- #En este caso, la fuente de video es la webcam del ordenador
- camera = cv2.VideoCapture(0)
- ret,frame = camera.read()
- if ret:
- assert not isinstance(frame,type(None)), 'frame not found'
- H,W = frame.shape[:2]
- #Se cargan las imágenes de la bateria y el platillo,
- #y se redimensionan estas imagenes a 200x100 pixeles
- Hatt = cv2.resize(cv2.imread('./images/ridecymbal.png'),(200,100),interpolation=cv2.INTER_CUBIC)
- Snare = cv2.resize(cv2.imread('./images/snaredrum.png'),(200,100),interpolation=cv2.INTER_CUBIC)
- #Se establecen las posiciones en las que deben colocarse ambas imágenes
- Hatt_center = [np.shape(frame)[1]*2//8,np.shape(frame)[0]*6//8]
- Snare_center = [np.shape(frame)[1]*6//8,np.shape(frame)[0]*6//8]
- Hatt_thickness = [200,100]
- Hatt_top = [Hatt_center[0]-Hatt_thickness[0]//2,Hatt_center[1]-Hatt_thickness[1]//2]
- Hatt_btm = [Hatt_center[0]+Hatt_thickness[0]//2,Hatt_center[1]+Hatt_thickness[1]//2]
- Snare_thickness = [200,100]
- Snare_top = [Snare_center[0]-Snare_thickness[0]//2,Snare_center[1]-Snare_thickness[1]//2]
- Snare_btm = [Snare_center[0]+Snare_thickness[0]//2,Snare_center[1]+Snare_thickness[1]//2]
- #Se selecciona el tipo de tracker a usar
- #Se establece uno por defecto, para cambiarlo será necesario
- #modificar el código
- tracker = cv2.TrackerCSRT_create()
- ##Se selecciona en pantalla el objeto a trackear y se inicia el tracking
- bbox = cv2.selectROI(frame, False)
- ok = tracker.init(frame, bbox)
- while True:
- #Cada vez que se repite el bucle del programa, se adquiere un nuevo frame que tratar
- ret, frame = camera.read()
- if not(ret):
- break
- #Actualizo las coordenadas del tracker
- ok, bbox = tracker.update(frame)
- #Imprimo el rectángulo por pantalla
- if ok:
- pass
- p1 = (int(bbox[0]), int(bbox[1]))
- p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
- cv2.rectangle(frame, p1, p2, (0,255,0), 2, 1)
- else:
- cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
- #Para ambas regiones, se analiza si hay algun objeto de color azul
- #La funcion np.copy copia la región de la imagen deseada a una variable _ROI
- #La funcion ROICheck comprueba si hay algun objeto azul en la región, y en caso de que
- #lo haya, emite el sonido esperado
- if ROIcheck(Hatt_top, Hatt_btm, bbox, 2):
- cv2.rectangle(frame, (Hatt_top[0],Hatt_top[1]), (Hatt_btm[0],Hatt_btm[1]), (0,0,255), 4, 1)
- else:
- cv2.rectangle(frame, (Hatt_top[0],Hatt_top[1]), (Hatt_btm[0],Hatt_btm[1]), (255,0,0), 2, 1)
- if ROIcheck(Snare_top, Snare_btm, bbox, 1):
- cv2.rectangle(frame, (Snare_top[0],Snare_top[1]), (Snare_btm[0],Snare_btm[1]), (0,0,255), 4, 1)
- else:
- cv2.rectangle(frame, (Snare_top[0],Snare_top[1]), (Snare_btm[0],Snare_btm[1]), (255,0,0), 2, 1)
- #Se añaden a la imagen las figuras de la bateria y el platillo, con una cierta trasparencia
- frame[Snare_top[1]:Snare_btm[1],Snare_top[0]:Snare_btm[0]] = cv2.addWeighted(Snare, 1, frame[Snare_top[1]:Snare_btm[1],Snare_top[0]:Snare_btm[0]], 1, 0)
- frame[Hatt_top[1]:Hatt_btm[1],Hatt_top[0]:Hatt_btm[0]] = cv2.addWeighted(Hatt, 1, frame[Hatt_top[1]:Hatt_btm[1],Hatt_top[0]:Hatt_btm[0]], 1, 0)
- #Por último, se muestra la imagen en pantalla
- cv2.imshow('Ventana Principal',frame)
- key = cv2.waitKey(1) & 0xFF
- if key == ord("q"):
- break
- #Al finalizar el programa, se desbloquea la cámara web y se eliminan las ventanas generadas
- camera.release()
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement