Oppure

Loading
04/11/13 15:28
lorenzoscarrone
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:

#importo i moduli
import pygame
import pygame.camera
from PIL import Image
#inizializzo la libreria
pygame.init()
pygame.camera.init()
#la funzione list_cameras() restituisce una lista con tutte le webcam disponibili
elenco_camere = pygame.camera.list_cameras()
#e creo una Camera di nome webcam
webcam = pygame.camera.Camera(elenco_camere[1])
#attivo la webcam
webcam.start()
#definizioni delle variabili di grafica per l'accelerazione hardware
screen = pygame.display.set_mode((600,480), pygame.DOUBLEBUF | pygame.HWSURFACE)
pygame.display.set_caption("My webcam application")
surf = pygame.display.get_surface()

def get_event(events):    
    for event in events:
        if event.type == pygame.QUIT:
            exit()

while True:
    #catturo l'immagine e la salvo nella variabile img
    get_event(pygame.event.get())
    img=webcam.get_image()
   
    #scrivere codice o funzione per analizzare immagini
    pil_string_image = pygame.image.tostring(img, "RGBA",False)
    image = Image.fromstring("RGBA",(600,480),pil_string_image)
    pix = image.load()
    #analisi immagine
    #colore da riconoscere
    ##############################
    R,G,B = 255,255,255 #colore bianco
    dr,dg,db = 7,18,33  #scarti per le sfumature
    ############################## 
    #ottenere dati da immagine
    sqare_list_density = [] #mem densita' di colore in aree schermo
    k=40 #dimensione area di analisi immagine
    #creo reticolato
    ret_x = [] #mem le coord del reticolato
    ret_y = [] #mem le coord del reticolato
    for x in range(1,599,k):
        for y in range(1,479,k):
            ret_x.append(x)
            ret_y.append(y)
            
    #riconoscimento immagine
            #ciclo che calcola la densita' di colore presente in un'area k*k e la mem in sqare_list_density[]
    for x in range(1,599,k):
        for y in range(1,479,k):
            disp = 0
            if ((x-k)>=0)and((y-k)>=0):
                for xc in range(x-k,x,1):
                    for yc in range(y-k,y,1):
                        if((R-dr)<=pix[xc,yc][0]<=R)and((G-dg)<=pix[xc,yc][1]<=G)and((B-db)<=pix[xc,yc][2]<=B):
                            disp += 1
                sqare_list_density.append(disp)
    #analisi densita' reticolato
        #ottengo numero di elementi nella matrice
    num = -1 
    for n in sqare_list_density:
        num += 1       
    max_num = num
       #analizzo reticolato eliminando zone di densita' minore fino ad avere un solo valore della lista != 0
    while num != 0: 
        if (sqare_list_density[num]<=sqare_list_density[num-1]) :
            sqare_list_density[num] = 0
            num -= 1
        else:
            sqare_list_density[num-1] = 0
            num -= 1
    #disegna immagine a schermo
    surf.blit( img, (0,0))
    dx, dy = 0, 0
    #disegno del reticolato e posizionamento puntatore
    for n in range(max_num):
        pygame.draw.line(surf,[255,0,0],(0,ret_y[n]),(600,ret_y[n]),2)
        pygame.draw.line(surf,[255,0,0],(ret_x[n],0),(ret_x[n],480),2)
        if sqare_list_density[n] !=0 : #se il valore della lista != 0 da le coordinate del cerchio
           dx = ret_x[n]-(k/2)
           dy = ret_y[n]-(k/2)
    pygame.draw.circle(surf, (0,200,0), (dx,dy), (k/2)) 
    #Scrive a scermo il testo vite, points
    screen.blit( surf, (0,0) )   
    #Permette la visualizzazione di tutto
    pygame.display.flip()

pygame.camera.quit()
Ultima modifica effettuata da lorenzoscarrone 19/11/13 18:38
aaa
09/06/15 15:45
lorenzoscarrone
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

#Detect shapes

import SimpleCV

display = SimpleCV.Display()
#carico la webcam
cam = SimpleCV.Camera()
normaldisplay = True

def ObjectType( blobs_s ): #ritorna il testo contenente il nome della figura
	if ( blobs_s.filter( [b.isCircle(0.2) for b in blobs_s] ) ):
		return "-- circle detect --"
	elif ( blobs_s.filter( [b.isRectangle(0.2) for b in blobs_s] ) ):
		return "-- rectangle detect --"
	else :
		return ""

while  display.isNotDone():
	if display.mouseRight:
		normaldisplay = not(normaldisplay)
		print "Display Mode:", "Normal" if normaldisplay else "Segmented" 
	
	img = cam.getImage().flipHorizontal()
	dist = img.colorDistance(SimpleCV.Color.BLACK).dilate(2)
	segmented = dist.stretch(200,255)
	blobs = segmented.findBlobs()
	img.dl().selectFont('Arial')
	text = ObjectType(blobs)

	if blobs:
		shape = blobs.filter([b.isCircle(0.2) for b in blobs]) or blobs.filter([b.isRectangle(0.2) for b in blobs])
		if shape:
			img.drawCircle( (shape[-1].x, shape[-1].y), shape[-1].radius(), SimpleCV.Color.RED, 3 )
			#Quadrato attorno circonferenza
			radius = shape[-1].radius()
			tL = (shape[-1].x-radius, shape[-1].y-radius)
			tR = (shape[-1].x+radius, shape[-1].y-radius)
			dR = (shape[-1].x+radius, shape[-1].y+radius)
			dL = (shape[-1].x-radius, shape[-1].y+radius)
			
			img.drawLine(tL, tR, color=(0, 200, 0), thickness=1)
			img.drawLine(tR, dR, color=(0, 200, 0), thickness=1)
			img.drawLine(dR, dL, color=(0, 200, 0), thickness=1)
			img.drawLine(dL, tL, color=(0, 200, 0), thickness=1)
			#Testo identificativo
			dist = len(text)*(7/2)
			img.drawText( text , shape[-1].x-dist, 
								 shape[-1].y-shape[-1].radius()-30, 
								 color=(0, 255, 0), fontsize=16 )

	if normaldisplay:
		img.show()
	else:
		segmented.show()
aaa