Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Python - problema con l'analisi di immagini da webcam
Forum - Python - problema con l'analisi di immagini da webcam

Avatar
lorenzoscarrone (Normal User)
Pro


Messaggi: 92
Iscritto: 16/11/2011

Segnala al moderatore
Postato alle 16:28
Lunedì, 04/11/2013
ho fatto un programma che dovrebbe riconoscere un colore preso da un'immagine webcam, e posizionare un puntatore in quel punto in questo caso il puntatore è una palla rossa.
ma il problema è che il puntatore si muove solo verticalmente, e il reticolato che ho disegnato a schermo non risulta completo.

vi posto il codice e il programma in un zip, per capire dov'è che sbaglio:

Codice sorgente - presumibilmente Python

  1. #importo i moduli
  2. import pygame
  3. import pygame.camera
  4. from PIL import Image
  5. #inizializzo la libreria
  6. pygame.init()
  7. pygame.camera.init()
  8. #la funzione list_cameras() restituisce una lista con tutte le webcam disponibili
  9. elenco_camere = pygame.camera.list_cameras()
  10. #e creo una Camera di nome webcam
  11. webcam = pygame.camera.Camera(elenco_camere[1])
  12. #attivo la webcam
  13. webcam.start()
  14. #definizioni delle variabili di grafica per l'accelerazione hardware
  15. screen = pygame.display.set_mode((600,480), pygame.DOUBLEBUF | pygame.HWSURFACE)
  16. pygame.display.set_caption("My webcam application")
  17. surf = pygame.display.get_surface()
  18.  
  19. def get_event(events):    
  20.     for event in events:
  21.         if event.type == pygame.QUIT:
  22.             exit()
  23.  
  24. while True:
  25.     #catturo l'immagine e la salvo nella variabile img
  26.     get_event(pygame.event.get())
  27.     img=webcam.get_image()
  28.    
  29.     #scrivere codice o funzione per analizzare immagini
  30.     pil_string_image = pygame.image.tostring(img, "RGBA",False)
  31.     image = Image.fromstring("RGBA",(600,480),pil_string_image)
  32.     pix = image.load()
  33.     #analisi immagine
  34.     #colore da riconoscere
  35.     ##############################
  36.     R,G,B = 255,255,255 #colore bianco
  37.     dr,dg,db = 7,18,33  #scarti per le sfumature
  38.     ##############################
  39.     #ottenere dati da immagine
  40.     sqare_list_density = [] #mem densita' di colore in aree schermo
  41.     k=40 #dimensione area di analisi immagine
  42.     #creo reticolato
  43.     ret_x = [] #mem le coord del reticolato
  44.     ret_y = [] #mem le coord del reticolato
  45.     for x in range(1,599,k):
  46.         for y in range(1,479,k):
  47.             ret_x.append(x)
  48.             ret_y.append(y)
  49.            
  50.     #riconoscimento immagine
  51.             #ciclo che calcola la densita' di colore presente in un'area k*k e la mem in sqare_list_density[]
  52.     for x in range(1,599,k):
  53.         for y in range(1,479,k):
  54.             disp = 0
  55.             if ((x-k)>=0)and((y-k)>=0):
  56.                 for xc in range(x-k,x,1):
  57.                     for yc in range(y-k,y,1):
  58.                         if((R-dr)<=pix[xc,yc][0]<=R)and((G-dg)<=pix[xc,yc][1]<=G)and((B-db)<=pix[xc,yc][2]<=B):
  59.                             disp += 1
  60.                 sqare_list_density.append(disp)
  61.     #analisi densita' reticolato
  62.         #ottengo numero di elementi nella matrice
  63.     num = -1
  64.     for n in sqare_list_density:
  65.         num += 1      
  66.     max_num = num
  67.        #analizzo reticolato eliminando zone di densita' minore fino ad avere un solo valore della lista != 0
  68.     while num != 0:
  69.         if (sqare_list_density[num]<=sqare_list_density[num-1]) :
  70.             sqare_list_density[num] = 0
  71.             num -= 1
  72.         else:
  73.             sqare_list_density[num-1] = 0
  74.             num -= 1
  75.     #disegna immagine a schermo
  76.     surf.blit( img, (0,0))
  77.     dx, dy = 0, 0
  78.     #disegno del reticolato e posizionamento puntatore
  79.     for n in range(max_num):
  80.         pygame.draw.line(surf,[255,0,0],(0,ret_y[n]),(600,ret_y[n]),2)
  81.         pygame.draw.line(surf,[255,0,0],(ret_x[n],0),(ret_x[n],480),2)
  82.         if sqare_list_density[n] !=0 : #se il valore della lista != 0 da le coordinate del cerchio
  83.            dx = ret_x[n]-(k/2)
  84.            dy = ret_y[n]-(k/2)
  85.     pygame.draw.circle(surf, (0,200,0), (dx,dy), (k/2))
  86.     #Scrive a scermo il testo vite, points
  87.     screen.blit( surf, (0,0) )  
  88.     #Permette la visualizzazione di tutto
  89.     pygame.display.flip()
  90.  
  91. pygame.camera.quit()



lorenzoscarrone ha allegato un file: webcam.py.zip (1507 bytes)
Clicca qui per scaricare il file

Ultima modifica effettuata da lorenzoscarrone il 19/11/2013 alle 19:38
PM Quote
Avatar
lorenzoscarrone (Normal User)
Pro


Messaggi: 92
Iscritto: 16/11/2011

Segnala al moderatore
Postato alle 17:45
Martedì, 09/06/2015
Alla fine ci ho rinunciato e mi sono messo ad usare la libreria SimpleCV , comunque posto lo stesso quello che volevo fare, però realizzato con SimpleCV

Codice sorgente - presumibilmente Python

  1. #Detect shapes
  2.  
  3. import SimpleCV
  4.  
  5. display = SimpleCV.Display()
  6. #carico la webcam
  7. cam = SimpleCV.Camera()
  8. normaldisplay = True
  9.  
  10. def ObjectType( blobs_s ): #ritorna il testo contenente il nome della figura
  11.         if ( blobs_s.filter( [b.isCircle(0.2) for b in blobs_s] ) ):
  12.                 return "-- circle detect --"
  13.         elif ( blobs_s.filter( [b.isRectangle(0.2) for b in blobs_s] ) ):
  14.                 return "-- rectangle detect --"
  15.         else :
  16.                 return ""
  17.  
  18. while  display.isNotDone():
  19.         if display.mouseRight:
  20.                 normaldisplay = not(normaldisplay)
  21.                 print "Display Mode:", "Normal" if normaldisplay else "Segmented"
  22.        
  23.         img = cam.getImage().flipHorizontal()
  24.         dist = img.colorDistance(SimpleCV.Color.BLACK).dilate(2)
  25.         segmented = dist.stretch(200,255)
  26.         blobs = segmented.findBlobs()
  27.         img.dl().selectFont('Arial')
  28.         text = ObjectType(blobs)
  29.  
  30.         if blobs:
  31.                 shape = blobs.filter([b.isCircle(0.2) for b in blobs]) or blobs.filter([b.isRectangle(0.2) for b in blobs])
  32.                 if shape:
  33.                         img.drawCircle( (shape[-1].x, shape[-1].y), shape[-1].radius(), SimpleCV.Color.RED, 3 )
  34.                         #Quadrato attorno circonferenza
  35.                         radius = shape[-1].radius()
  36.                         tL = (shape[-1].x-radius, shape[-1].y-radius)
  37.                         tR = (shape[-1].x+radius, shape[-1].y-radius)
  38.                         dR = (shape[-1].x+radius, shape[-1].y+radius)
  39.                         dL = (shape[-1].x-radius, shape[-1].y+radius)
  40.                        
  41.                         img.drawLine(tL, tR, color=(0, 200, 0), thickness=1)
  42.                         img.drawLine(tR, dR, color=(0, 200, 0), thickness=1)
  43.                         img.drawLine(dR, dL, color=(0, 200, 0), thickness=1)
  44.                         img.drawLine(dL, tL, color=(0, 200, 0), thickness=1)
  45.                         #Testo identificativo
  46.                         dist = len(text)*(7/2)
  47.                         img.drawText( text , shape[-1].x-dist,
  48.                                                                  shape[-1].y-shape[-1].radius()-30,
  49.                                                                  color=(0, 255, 0), fontsize=16 )
  50.  
  51.         if normaldisplay:
  52.                 img.show()
  53.         else:
  54.                 segmented.show()


PM Quote