
import imageio
import numpy
from matplotlib.pyplot import *
import sys
                

def coloriage_pixel(image,shape,seuil,valeur,i,j):
    image[j][i] = valeur
    voisins = [(i+1,j),(i-1,j),(i,j-1),(i,j+1)]
    for pixel in voisins:
        (k,l) = pixel
        if k>=0 and k<shape[1] and l>=0 and l<shape[0]:
            if image[l][k]>seuil:
                coloriage_pixel(image,shape,seuil,valeur,k,l)
                

img = imageio.imread("../../../../figures/image/extraction/regions/contours3.png")
rouge = img[:,:,0]
vert = img[:,:,1]
bleu = img[:,:,2]
figure(figsize=(4,4))
imshow(rouge,cmap='gray',vmin=0,vmax=255)

                

sys.setrecursionlimit(rouge.size)
                

image = rouge.copy()
coloriage_pixel(image,image.shape,110,100,40,40)
figure(figsize=(4,4))
imshow(image,cmap='gray',vmin=0,vmax=255)
                

def coloriage_pixel_pile(image,shape,seuil,valeur,pile,i,j):
   image[j][i] = valeur
   voisins = [(i+1,j),(i-1,j),(i,j-1),(i,j+1)]
   for pixel in voisins:
        (k,l) = pixel
        if k>=0 and k<shape[1] and l>=0 and l<shape[0]:
            if image[l][k]>seuil:
                image[l][k] = valeur
                pile.append(pixel)
                  

def coloriage_region(image,shape,seuil,valeur,i0,j0):
    if valeur>seuil:
        seuil = valeur
    pile = [(i0,j0)]
    while len(pile)>0:
        (i,j) = pile.pop()
        coloriage_pixel_pile(image,shape,seuil,valeur,pile,i,j)
                   

image = rouge.copy()
coloriage_region(image,image.shape,110,100,40,40)
figure(figsize=(4,4))
imshow(image,cmap='gray',vmin=0,vmax=255)
                   

def coloriage_pixel_pile(image,result,shape,seuil,valeur,pile,i,j):
    image[j][i] = valeur
    result[j][i] = 255
    voisins = [(i+1,j),(i-1,j),(i,j-1),(i,j+1)]
    for pixel in voisins:
        (k,l) = pixel
        if k>=0 and k<shape[1] and l>=0 and l<shape[0]:
            if image[l][k]>seuil:
                image[l][k] = valeur
                pile.append(pixel)
               

def analyse(image,seuil):
    shape = image.shape
    Nx = shape[1]
    Ny = shape[0]
    compteur = 0
    positions = []
    result = numpy.zeros((Ny,Nx),dtype=numpy.uint8)
    for y in range(Ny):
        for x in range(Nx):
            if image[y][x] > seuil:
                compteur += 1
                pile = [(x,y)]
                si = 0
                sj = 0
                npix = 0
                while len(pile)>0:
                    (i,j) = pile.pop()
                    si += i
                    sj += j
                    npix += 1
                    coloriage_pixel_pile(image,result,shape,seuil,0,pile,i,j)
                xb = si*1.0/npix
                yb = sj*1.0/npix
                positions.append((xb,yb,npix))
    print("Nombre de taches : %d"%compteur)
    for p in positions:
        print("x=%f, y=%f, npix=%d"%(p[0],p[1],p[2]))
    return (positions,result)
               

img = imageio.imread("../../../../figures/image/extraction/regions/points.png")
rouge = img[:,:,0]
vert = img[:,:,1]
bleu = img[:,:,2]
image = rouge.copy()
(positions,result) = analyse(image,130)

shape = image.shape
figure(figsize=(6,6))
for p in positions:
    plot([p[0]],[shape[0]-p[1]],'ob')
axis([0,shape[1],0,shape[0]])
               

img = imageio.imread("../../../../figures/image/extraction/regions/sky3.jpeg")
rouge = img[:,:,0]
vert = img[:,:,1]
bleu = img[:,:,2]
figure(figsize=(7,7))
imshow(rouge,cmap='gray',vmin=0,vmax=255)
                  

image = rouge.copy()
(positions,result) = analyse(image,130)

shape = image.shape
figure(figsize=(7,7))
for p in positions:
    x = p[0]
    y = shape[0]-p[1]
    plot([x],[y],'.b')
    text(x,y,"%d"%p[2])

axis([0,shape[1],0,shape[0]])
title("rouge")
                   

image = bleu.copy()
(positions,result) = analyse(image,130)

shape = image.shape
figure(figsize=(7,7))
for p in positions:
    x = p[0]
    y = shape[0]-p[1]
    plot([x],[y],'.b')
    text(x,y,"%d"%p[2])

axis([0,shape[1],0,shape[0]])
title("bleu")
                   

import sqlcl
import StringIO

ra = 150.0
dec = 0.0
width = 1.0/60*10.0
height = 1.0/60*10.0
ra1 = ra-width/2
ra2 = ra+width/2
dec1 = dec-height/2
dec2 = dec+height/2
"""
Magnitudes :
    U : 0.36 micrometres
    R : 0.64
    G : 0.52
    I : 0.79
"""
requeteSQL = "SELECT  ra,dec,psfMag_u,psfMag_g,psfMag_r,psfMag_i  FROM star\
            WHERE (ra BETWEEN %f AND %f)\
            AND (dec BETWEEN %f AND %f)\
            AND (psfMag_r BETWEEN 1 AND 19)"%(ra1,ra2,dec1,dec2)
result = sqlcl.query(requeteSQL).read()
print(result)
result = result.replace(',',' ')
data = numpy.loadtxt(StringIO.StringIO(result),skiprows=2,unpack=True)
ra = data[0]
dec = data[1]
mag_u = data[2]
mag_g = data[3]
mag_r = data[4]
mag_i = data[5]

figure(figsize=(7,7))
for i in range(ra.size):
    x = ra2-ra[i]
    y = dec[i]
    plot([x],[y],"ob")
    text(x,y,"%d"%(int(mag_r[i])))
xlabel("ra (deg)")
ylabel("dec (deg)")
for p in positions:
    x = p[0]*width/shape[1]
    y = dec1+(shape[0]-p[1])*height/shape[0]
    plot([x],[y],'xr')
                      
