Advertisement
Guest User

Untitled

a guest
Apr 10th, 2020
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.21 KB | None | 0 0
  1. import numpy as np
  2. import time
  3. import cv2
  4. from pygame import mixer
  5.  
  6. from shapely.geometry import Polygon
  7.  
  8. verbose = False
  9. drumFile='sounds/snaredrum.wav'
  10. cymbalFile='sounds/ridecymbal.ogg'
  11.  
  12. #La funcion playInstrument reproduce el sonido indicado
  13. def playInstrument(sound):
  14.     #En función de en que region de interes se ha activado la funcion
  15.         #se reproduce el sonido adecuado
  16.     if sound==1:
  17.         drum_clap.play()       
  18.     elif sound==2:
  19.         drum_snare.play()
  20.         time.sleep(0.001)
  21.  
  22. #La funcion ROICheck ya no tiene que comprobar la existencia de un color
  23.     #si no si las BBox de la ROI y del objeto trackeado se superponen
  24.     #lo que significaría que se debe activar el sonido
  25. def ROIcheck(eq1, eq2, bbox ,sound):
  26.  
  27.     boxA = [eq1[0], eq2[1], eq2[0]-eq1[0],  eq2[1]-eq1[1]]  
  28.     boxB = [bbox[0], bbox[1]+bbox[3], bbox[2], bbox[3]]
  29.    
  30.    
  31.    
  32.     poly_1 = Polygon([[eq1[0], eq2[1]], [eq2[0], eq2[1]], [eq2[0], eq1[1]], [eq1[0], eq1[1]]])
  33.     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]] ])
  34.    
  35.    
  36.     print(poly_1.intersection(poly_2).area)
  37.     if poly_1.intersection(poly_2).area > 0:
  38.         playInstrument(sound)
  39.         return True
  40.    
  41.  
  42.  
  43.  
  44. if __name__ == '__main__' :
  45.     #El código comienza inicializando unas funciones del paquete pygame,
  46.         #necesario para reproducir los sonidos de los instrumentos
  47.     mixer.init()
  48.     drum_clap = mixer.Sound(drumFile)
  49.     drum_snare = mixer.Sound(cymbalFile)
  50.  
  51.     #Posteriormente, se inicia la lectura de video de openCV
  52.     #En este caso, la fuente de video es la webcam del ordenador
  53.     camera = cv2.VideoCapture(0)
  54.     ret,frame = camera.read()
  55.     if ret:
  56.         assert not isinstance(frame,type(None)), 'frame not found'
  57.         H,W = frame.shape[:2]
  58.  
  59.     #Se cargan las imágenes de la bateria y el platillo,
  60.         #y se redimensionan estas imagenes a 200x100 pixeles
  61.     Hatt = cv2.resize(cv2.imread('./images/ridecymbal.png'),(200,100),interpolation=cv2.INTER_CUBIC)
  62.     Snare = cv2.resize(cv2.imread('./images/snaredrum.png'),(200,100),interpolation=cv2.INTER_CUBIC)
  63.  
  64.     #Se establecen las posiciones en las que deben colocarse ambas imágenes
  65.     Hatt_center = [np.shape(frame)[1]*2//8,np.shape(frame)[0]*6//8]
  66.     Snare_center = [np.shape(frame)[1]*6//8,np.shape(frame)[0]*6//8]
  67.     Hatt_thickness = [200,100]
  68.     Hatt_top = [Hatt_center[0]-Hatt_thickness[0]//2,Hatt_center[1]-Hatt_thickness[1]//2]
  69.     Hatt_btm = [Hatt_center[0]+Hatt_thickness[0]//2,Hatt_center[1]+Hatt_thickness[1]//2]
  70.     Snare_thickness = [200,100]
  71.     Snare_top = [Snare_center[0]-Snare_thickness[0]//2,Snare_center[1]-Snare_thickness[1]//2]
  72.     Snare_btm = [Snare_center[0]+Snare_thickness[0]//2,Snare_center[1]+Snare_thickness[1]//2]
  73.    
  74.    
  75.     #Se selecciona el tipo de tracker a usar
  76.     #Se establece uno por defecto, para cambiarlo será necesario
  77.         #modificar el código
  78.     tracker = cv2.TrackerCSRT_create()
  79.    
  80.    
  81.     ##Se selecciona en pantalla el objeto a trackear y se inicia el tracking
  82.     bbox = cv2.selectROI(frame, False)
  83.     ok = tracker.init(frame, bbox)
  84.    
  85.    
  86.  
  87.     while True:
  88.         #Cada vez que se repite el bucle del programa, se adquiere un nuevo frame que tratar
  89.         ret, frame = camera.read()
  90.         if not(ret):
  91.             break
  92.        
  93.         #Actualizo las coordenadas del tracker
  94.         ok, bbox = tracker.update(frame)
  95.        
  96.         #Imprimo el rectángulo por pantalla
  97.         if ok:
  98.             pass
  99.             p1 = (int(bbox[0]), int(bbox[1]))
  100.             p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
  101.            
  102.             cv2.rectangle(frame, p1, p2, (0,255,0), 2, 1)
  103.         else:
  104.             cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
  105.         #Para ambas regiones, se analiza si hay algun objeto de color azul
  106.         #La funcion np.copy copia la región de la imagen deseada a una variable _ROI
  107.         #La funcion ROICheck comprueba si hay algun objeto azul en la región, y en caso de que  
  108.             #lo haya, emite el sonido esperado
  109.         if ROIcheck(Hatt_top, Hatt_btm, bbox, 2):
  110.             cv2.rectangle(frame, (Hatt_top[0],Hatt_top[1]), (Hatt_btm[0],Hatt_btm[1]), (0,0,255), 4, 1)
  111.         else:
  112.             cv2.rectangle(frame, (Hatt_top[0],Hatt_top[1]), (Hatt_btm[0],Hatt_btm[1]), (255,0,0), 2, 1)
  113.        
  114.        
  115.        
  116.         if ROIcheck(Snare_top, Snare_btm, bbox, 1):
  117.             cv2.rectangle(frame, (Snare_top[0],Snare_top[1]), (Snare_btm[0],Snare_btm[1]), (0,0,255), 4, 1)
  118.         else:
  119.             cv2.rectangle(frame, (Snare_top[0],Snare_top[1]), (Snare_btm[0],Snare_btm[1]), (255,0,0), 2, 1)
  120.  
  121.        
  122.        
  123.  
  124.         #Se añaden a la imagen las figuras de la bateria y el platillo, con una cierta trasparencia
  125.         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)
  126.         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)
  127.        
  128.         #Por último, se muestra la imagen en pantalla
  129.         cv2.imshow('Ventana Principal',frame)
  130.         key = cv2.waitKey(1) & 0xFF
  131.  
  132.         if key == ord("q"):
  133.             break
  134.            
  135.     #Al finalizar el programa, se desbloquea la cámara web y se eliminan las ventanas generadas
  136.     camera.release()
  137.     cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement