Example #1
0
def data_from_image(im, classes, mask, limits=[0., 1.]):
    """ This function extracts the data from a image, based on the classes and a mask. 
      Once the data is masked, a look-up-table is used to set values to the classes. 
  """
    import time
    N = int(basic.nonan(classes).max() + 1)
    # zero is a class...
    classes[mask] = np.nan
    classLimits = np.linspace(np.min(limits), np.max(limits), N)

    cmax = 2**np.round(np.log2(im.max()))
    imSingle = im[:, :, 0] * (cmax**0) + im[:, :, 1] * (
        cmax**1) + im[:, :, 2] * (cmax**2.)
    data = np.zeros(imSingle.shape)
    t0 = 0
    for k in xrange(N - 1):
        #for each class do a linear interpolation
        if np.any(classes == k):
            data[classes == k] = basic.rescale(imSingle[classes == k],
                                               classLimits[k:k + 2],
                                               quiet=True)
        if basic.progresstime(t0):
            basic.progress(k, N)
            t0 = time.time()
    data[mask] = np.nan
    return data
Example #2
0
    def onclick(event):
        P.figure(fh.number)
        P.clf()
        #ax = P.gca()
        #inv = ax.transData.inverted()
        #A=inv.transform((event.x,  event.y))
        #A[1]=np.int(np.round((1-A[1])*array2d.shape[1]))
        #A[0]=np.int(np.round((A[0])*array2d.shape[0]))
        try:
            y = np.round(event.xdata)
        except:
            return
        x = np.round(event.ydata)
        #ARRAY MAPPING IS first axis y(rows) and second axis is cols (x)
        if all(np.isnan(array3d[x, y, :])):
            #if there are no points to plot (all nan) then return
            return

        #Plot second scatter data.
        if array3d2 is not None:
            if isinstance(array3d2, list):
                if yerror3d is None:
                    w = np.ones(array3d[x, y, :].shape)
                else:
                    w = basic.rescale(1. / yerror3d[x, y, :], [1, 2])
                markers = ['*', '+', 's', 'd', 'x', 'v', '<', '>', '^']
                m = 0
                for arr in array3d2:
                    print("%d, %d, %d" % (x, y, m))
                    P.scatter(xScat, arr[x, y, :], marker=markers[m])
                    idx = ~(np.isnan(arr[x, y, :])
                            | np.isnan(array3d[x, y, :]))
                    #c=insar.crosscorrelate(basic.nonan(w[idx]*arr[x, y,idx]),basic.nonan(w[idx]*array3d[x, y,idx]))
                    slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(
                        basic.nonan(w[idx] * arr[x, y, idx]),
                        basic.nonan(w[idx] * array3d[x, y, idx]))
                    P.annotate(str("r2[%s]: %0.2f" % (markers[m], r_value)),
                               (0, 0.9 - m * 0.05),
                               xycoords='axes fraction')
                    m = m + 1
            else:
                if xerror3d2 is None:
                    xerr = None
                else:
                    xerr = xerror3d2[x, y, :]
                if yerror3d2 is None:
                    yerr = None
                else:
                    yerr = yerror3d2[x, y, :]
                P.errorbar(xScat,
                           array3d2[x, y, :],
                           xerr=xerr,
                           yerr=yerr,
                           marker='*',
                           fmt='o')

        #Plot function result as scatter data.
        p = None
        if fn is not None:
            if fn == 'linear_amplitude_annual':
                dataMask = ~np.isnan(array3d[x, y, :])
                p0 = np.array([1, 0, 0, basic.nonan(array3d[x, y, :]).mean()])
                fitfun = lambda p: (p[0] + p[1] * xScat[dataMask] / 365.
                                    ) * np.cos(2 * np.pi * xScat[dataMask] /
                                               365. + p[2]) + p[3]
                xScat2 = np.linspace(xScat.min(), xScat.max())
                fitfun2 = lambda p: (p[0] + p[1] * xScat2 / 365.) * np.cos(
                    2 * np.pi * xScat2 / 365. + p[2]) + p[3]
                #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p)));
                if yerror3d is None:
                    w = np.ones(array3d[x, y, :].shape)
                else:
                    w = basic.rescale(1. / yerror3d[x, y, :], [1, 2])
                errfun = lambda p: basic.nonan(w * array3d[x, y, :]) - w[
                    dataMask] * fitfun(p)
                #p=scipy.optimize.fmin_powell(errfun, p0)
                p = scipy.optimize.leastsq(errfun, p0)
                p = p[0]
                P.scatter(xScat[dataMask], fitfun(p), marker='^')
                sortedxy = np.squeeze(np.dstack([xScat2, fitfun2(p)]))
                sortedxy = sortedxy[sortedxy[:, 0].argsort(), :]
                P.plot(sortedxy[:, 0], sortedxy[:, 1])
                slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(
                    basic.nonan(w * array3d[x, y, :]), w[dataMask] * fitfun(p))
                P.annotate(
                    str("a0:%0.2f\na1:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" %
                        (p[0], p[1], p[2], p[3], r_value**2.)), (0.8, 0.8),
                    xycoords='axes fraction')
            elif fn == 'quadratic_amplitude_annual':
                dataMask = ~np.isnan(array3d[x, y, :])
                p0 = np.array(
                    [1, 0, 0, 0,
                     basic.nonan(array3d[x, y, :]).mean()])
                fitfun = lambda p: (p[0] + p[1] * xScat[dataMask] / 365. + p[
                    2] * (xScat[dataMask] / 365.)**2.) * np.cos(
                        2 * np.pi * xScat[dataMask] / 365. + p[3]) + p[4]
                xScat2 = np.linspace(xScat.min(), xScat.max())
                fitfun2 = lambda p: (p[0] + p[1] * xScat2 / 365. + p[2] * (
                    xScat2 / 365.)**2.) * np.cos(2 * np.pi * xScat2 / 365. + p[
                        3]) + p[4]
                #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p)));
                if yerror3d is None:
                    w = np.ones(array3d[x, y, :].shape)
                else:
                    w = basic.rescale(1. / yerror3d[x, y, :], [1, 2])
                errfun = lambda p: basic.nonan(w * array3d[x, y, :]) - w[
                    dataMask] * fitfun(p)
                #p=scipy.optimize.fmin_powell(errfun, p0)
                p = scipy.optimize.leastsq(errfun, p0)
                p = p[0]
                P.scatter(xScat[dataMask], fitfun(p), marker='^')
                sortedxy = np.squeeze(np.dstack([xScat2, fitfun2(p)]))
                sortedxy = sortedxy[sortedxy[:, 0].argsort(), :]
                P.plot(sortedxy[:, 0], sortedxy[:, 1])
                slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(
                    basic.nonan(w * array3d[x, y, :]), w[dataMask] * fitfun(p))
                P.annotate(str(
                    "a0:%0.2f\na1:%0.2f\na2:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f"
                    % (p[0], p[1], p[2], p[3], p[4], r_value**2.)), (0.8, 0.8),
                           xycoords='axes fraction')

            elif fn == 'annual':
                dataMask = ~np.isnan(array3d[x, y, :])
                p0 = np.array([1, 1, basic.nonan(array3d[x, y, :]).mean()])
                fitfun = lambda p: p[0] * np.cos(2 * np.pi * xScat[dataMask] /
                                                 365. + p[1]) + p[2]
                xScat2 = np.linspace(xScat.min(), xScat.max())
                fitfun2 = lambda p: p[0] * np.cos(2 * np.pi * xScat2 / 365. +
                                                  p[1]) + p[2]
                #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p)));
                if yerror3d is None:
                    w = np.ones(array3d[x, y, :].shape)
                else:
                    w = basic.rescale(1. / yerror3d[x, y, :], [1, 2])
                errfun = lambda p: basic.nonan(w * array3d[x, y, :]) - w[
                    dataMask] * fitfun(p)
                #p=scipy.optimize.fmin_powell(errfun, p0)
                p = scipy.optimize.leastsq(errfun, p0)
                p = p[0]
                P.scatter(xScat[dataMask], fitfun(p), marker='^')
                sortedxy = np.squeeze(np.dstack([xScat2, fitfun2(p)]))
                sortedxy = sortedxy[sortedxy[:, 0].argsort(), :]
                P.plot(sortedxy[:, 0], sortedxy[:, 1])
                slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(
                    basic.nonan(w * array3d[x, y, :]), w[dataMask] * fitfun(p))
                P.annotate(str("amp:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" %
                               (p[0], p[1], p[2], r_value**2.)), (0.8, 0.8),
                           xycoords='axes fraction')
            else:
                p = None
                P.scatter(xScat, fn(xScat), marker='^')
        #convert axis to date...
        if dateaxis:
            try:
                P.figure(fh.number).axes[0].xaxis_date(tz=None)
                P.figure(fh.number).autofmt_xdate()
            except:
                pass
        #change x y to xMap, yMap
        if yMap is not None:
            xM = ya * x + yb
        else:
            xM = x
        if xMap is not None:
            yM = xa * (y) + xb
        else:
            yM = y
        #x and y are flipped in the try/except block above. So Flip again.
        #if p is not None:
        #    P.title("x,y,[]: " + str(yM) + ", " + str(xM) + ', ' + str(p) )
        #else:
        P.title("x,y,z,z.std: " + str(yM) + ", " + str(xM) + ', ' +
                str(array2d[x, y]) + ', ' +
                str(np.std(basic.nonan(array3d[x, y, :]))))

        # rotate and align the tick labels so they look better
        #P.figure(fh.number).autofmt_xdate()
        # use a more precise date string for the x axis locations in the
        # toolbar
        #P.gca().fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

        if xerror3d is None:
            xerr = None
        else:
            xerr = xerror3d[x, y, :]
        if yerror3d is None:
            yerr = None
        else:
            yerr = yerror3d[x, y, :]
        if modelError:
            yerr = yerror3d[x, y, :]
            yerr[dataMask] = errfun(p)

        P.errorbar(xScat, array3d[x, y, :], xerr=xerr, yerr=yerr, fmt='ro')
        if ylimScat is not None:
            P.ylim(ylimScat)
Example #3
0
    def onclick(event):
        P.figure(fh.number);
        P.clf();
        #ax = P.gca()
        #inv = ax.transData.inverted()
        #A=inv.transform((event.x,  event.y))
        #A[1]=np.int(np.round((1-A[1])*array2d.shape[1])) 
        #A[0]=np.int(np.round((A[0])*array2d.shape[0]))
        try:
            y=np.round(event.xdata);
        except:
            return
        x=np.round(event.ydata);        
        #ARRAY MAPPING IS first axis y(rows) and second axis is cols (x)
        if all(np.isnan(array3d[x, y,:])):
            #if there are no points to plot (all nan) then return
            return
        
        #Plot second scatter data.
        if array3d2 is not None:        
            if isinstance(array3d2, list):
                if yerror3d is None:
                    w=np.ones(array3d[x, y,:].shape);
                else:
                    w=basic.rescale(1./yerror3d[x,y,:], [1,2])
                markers=['*','+','s','d','x','v','<','>','^']
                m=0;
                for arr in array3d2:  
                    print ("%d, %d, %d" % (x,y,m))                  
                    P.scatter(xScat, arr[x, y,:], marker=markers[m]);
                    idx=~( np.isnan(arr[x, y,:]) | np.isnan(array3d[x, y,:]))
                    #c=insar.crosscorrelate(basic.nonan(w[idx]*arr[x, y,idx]),basic.nonan(w[idx]*array3d[x, y,idx]))
                    slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w[idx]*arr[x, y,idx]), basic.nonan(w[idx]*array3d[x, y,idx]))
                    P.annotate(str("r2[%s]: %0.2f" % (markers[m],r_value)), (0,0.9-m*0.05), xycoords='axes fraction')                    
                    m=m+1;
            else:            
                if xerror3d2 is None:
                    xerr=None;
                else:
                    xerr=xerror3d2[x,y,:]
                if yerror3d2 is None:
                    yerr=None;
                else:
                    yerr=yerror3d2[x, y,:]
                P.errorbar(xScat,array3d2[x, y,:], xerr=xerr, yerr=yerr, marker='*', fmt='o');

        #Plot function result as scatter data.
        p=None            
        if fn is not None:
            if fn=='linear_amplitude_annual':
                dataMask=~np.isnan(array3d[x, y,:])
                p0=np.array([1,0,0,basic.nonan(array3d[x, y,:]).mean() ])
                fitfun=lambda p: (p[0]+p[1]*xScat[dataMask]/365. )* np.cos(2*np.pi*xScat[dataMask]/365.+p[2]) + p[3]
                xScat2=np.linspace(xScat.min(),xScat.max())
                fitfun2=lambda p: (p[0]+p[1]*xScat2/365.) * np.cos(2*np.pi*xScat2/365.+p[2]) + p[3]
                #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p)));
                if yerror3d is None:
                    w=np.ones(array3d[x, y,:].shape);
                else:
                    w=basic.rescale(1./yerror3d[x,y,:], [1,2])
                errfun=lambda p: basic.nonan(w*array3d[x, y,:])-w[dataMask]*fitfun(p);
                #p=scipy.optimize.fmin_powell(errfun, p0)
                p=scipy.optimize.leastsq(errfun, p0);
                p=p[0];
                P.scatter(xScat[dataMask], fitfun(p), marker='^');                
                sortedxy=  np.squeeze(np.dstack([xScat2, fitfun2(p)]));
                sortedxy=sortedxy[sortedxy[:,0].argsort(),:]
                P.plot(sortedxy[:,0], sortedxy[:,1]);
                slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w*array3d[x, y,:]),w[dataMask]*fitfun(p))
                P.annotate(str("a0:%0.2f\na1:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], p[3], r_value**2.)), (0.8,0.8), xycoords='axes fraction')
            elif fn=='quadratic_amplitude_annual':
                dataMask=~np.isnan(array3d[x, y,:])
                p0=np.array([1,0,0,0,basic.nonan(array3d[x, y,:]).mean() ])
                fitfun=lambda p: (p[0]+p[1]*xScat[dataMask]/365.+p[2]*(xScat[dataMask]/365.)**2. )* np.cos(2*np.pi*xScat[dataMask]/365.+p[3]) + p[4]
                xScat2=np.linspace(xScat.min(),xScat.max())
                fitfun2=lambda p: (p[0]+p[1]*xScat2/365.+p[2]*(xScat2/365.)**2.) * np.cos(2*np.pi*xScat2/365.+p[3]) + p[4]
                #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p)));
                if yerror3d is None:
                    w=np.ones(array3d[x, y,:].shape);
                else:
                    w=basic.rescale(1./yerror3d[x,y,:], [1,2])
                errfun=lambda p: basic.nonan(w*array3d[x, y,:])-w[dataMask]*fitfun(p);
                #p=scipy.optimize.fmin_powell(errfun, p0)
                p=scipy.optimize.leastsq(errfun, p0);
                p=p[0];
                P.scatter(xScat[dataMask], fitfun(p), marker='^');                
                sortedxy=  np.squeeze(np.dstack([xScat2, fitfun2(p)]));
                sortedxy=sortedxy[sortedxy[:,0].argsort(),:]
                P.plot(sortedxy[:,0], sortedxy[:,1]);
                slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w*array3d[x, y,:]),w[dataMask]*fitfun(p))
                P.annotate(str("a0:%0.2f\na1:%0.2f\na2:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], p[3], p[4], r_value**2.)), (0.8,0.8), xycoords='axes fraction')


            elif fn=='annual':
                dataMask=~np.isnan(array3d[x, y,:])
                p0=np.array([1,1,basic.nonan(array3d[x, y,:]).mean() ])
                fitfun=lambda p: p[0]* np.cos(2*np.pi*xScat[dataMask]/365.+p[1]) + p[2]
                xScat2=np.linspace(xScat.min(),xScat.max())
                fitfun2=lambda p: p[0]* np.cos(2*np.pi*xScat2/365.+p[1]) + p[2]
                #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p)));
                if yerror3d is None:
                    w=np.ones(array3d[x, y,:].shape);
                else:
                    w=basic.rescale(1./yerror3d[x,y,:], [1,2])
                errfun=lambda p: basic.nonan(w*array3d[x, y,:])-w[dataMask]*fitfun(p);
                #p=scipy.optimize.fmin_powell(errfun, p0)
                p=scipy.optimize.leastsq(errfun, p0);
                p=p[0];
                P.scatter(xScat[dataMask], fitfun(p), marker='^');                
                sortedxy=  np.squeeze(np.dstack([xScat2, fitfun2(p)]));
                sortedxy=sortedxy[sortedxy[:,0].argsort(),:]
                P.plot(sortedxy[:,0], sortedxy[:,1]);
                slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w*array3d[x, y,:]),w[dataMask]*fitfun(p))
                P.annotate(str("amp:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], r_value**2.)), (0.8,0.8), xycoords='axes fraction')
            else:      
                p=None             
                P.scatter(xScat, fn(xScat), marker='^');       
        #convert axis to date...             
        if dateaxis:
            try:
                P.figure(fh.number).axes[0].xaxis_date(tz=None)
                P.figure(fh.number).autofmt_xdate()
            except:
                pass
        #change x y to xMap, yMap
        if yMap is not None:
            xM=ya*x+yb;
        else:
            xM=x;
        if xMap is not None:
            yM=xa*(y)+xb;
        else:
            yM=y;
        #x and y are flipped in the try/except block above. So Flip again.
        #if p is not None:
        #    P.title("x,y,[]: " + str(yM) + ", " + str(xM) + ', ' + str(p) )
        #else:
        P.title("x,y,z,z.std: " + str(yM) + ", " + str(xM) + ', ' + str(array2d[x,y]) +', ' + str(np.std(basic.nonan(array3d[x, y,:]))) )
        
        # rotate and align the tick labels so they look better
        #P.figure(fh.number).autofmt_xdate()
        # use a more precise date string for the x axis locations in the
        # toolbar
        #P.gca().fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

        if xerror3d is None:
            xerr=None;
        else:
            xerr=xerror3d[x,y,:]
        if yerror3d is None:
            yerr=None;
        else:
            yerr=yerror3d[x, y,:]        
        if modelError:
            yerr=yerror3d[x, y,:] 
            yerr[dataMask]=errfun(p)
            
        P.errorbar(xScat,array3d[x, y,:], xerr=xerr, yerr=yerr, fmt='ro');
        if ylimScat is not None:
            P.ylim(ylimScat);
Example #4
0
import cv2
import carve, basic, merg

if __name__ == '__main__':
    img = cv2.imread('testdata/p1.jpg')
    overlay = carve.circular(img)
    overlay = basic.rescale(overlay, 0.1)

    frame = basic.rescale(cv2.imread('testdata/p1.jpg'), .3)
    output = merg.place(overlay, frame, 570, 100)
    basic.imshow(output)
Example #5
0
def writeCSV(ary,
             filename='kgiAlos.tif',
             rescale=None,
             dataformat="%f",
             lon=None,
             lat=None,
             nodata=None,
             grid=False,
             srs_proj4='+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'):
    '''writeAny(ary, geoTransform, format="GTiff", filename='kgiAlos.tif', rescale=None, format=gdal.GDT_Float64 ,lon=None, lat=None):
    ary: 2D array.
    geoTransform: [top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution]
    format: "GTiff" 
    rescale: [min max]: If given rescale ary values between min and max.
    
    If lon lat is specified set coord to None
    
    '''

    if coord is None:
        import scipy
        import scipy.linalg
        s = [sk / 10 for sk in ary.shape]
        ary10 = ary[::s[0], ::s[1]]
        lon10 = lon[::s[0], ::s[1]]
        lat10 = lat[::s[0], ::s[1]]
        #P.figure()
        #P.scatter(lon10.ravel(), lat10.ravel(), 5, ary10.ravel(), edgecolors='none')
        A = N.ones([N.multiply(*ary10.shape), 3])
        line, pixel = N.meshgrid(N.r_[0:ary.shape[0]:s[0]],
                                 N.r_[0:ary.shape[1]:s[1]])
        A[:, 1] = pixel.ravel()
        A[:, 2] = line.ravel()
        xlon = N.dot(scipy.linalg.pinv(A), lon10.ravel())
        xlat = N.dot(scipy.linalg.pinv(A), lat10.ravel())
        ##check flip flop
        #if xlon[1]<0: #flip lr
        #    ary=N.fliplr(ary)
        #
        #if xlat[2]>0: #flip ud
        #    ary=N.flipud(ary)
        coord = [xlon[0], xlon[2], xlon[1], xlat[0], xlat[2], xlat[1]]
        print coord
        #x=lon[0,0]
        #y=lat[0,0]
        #dx=lon[0,1]-lon[0,0]
        #dy=lat[1,0]-lat[0,0]
        #xrot=0.
        #yrot=0.
        #coord=[x,dx, xrot, y,yrot, dy]

        if grid:
            import scipy.interpolate
            LON, LAT = N.meshgrid(N.r_[lon.min():lon.max():abs(coord[1])],
                                  N.r_[lat.max():lat.min():-abs(coord[5])])
            #ary=P.griddata(lon.ravel(),lat.ravel(),ary.ravel(),LON,LAT);
            ary = scipy.interpolate.griddata(N.array(
                [lon.ravel(), lat.ravel()]).T,
                                             ary.ravel(), (LON, LAT),
                                             method='cubic')
            coord = [
                LON[0, 0],
                abs(coord[1]), 0, LAT[0, 0], 0, -abs(coord[5])
            ]
            print coord

    if rescale:
        import basic
        ary = basic.rescale(ary, rescale)

    # data exists in 'ary' with values range 0 - 255
    # Uncomment next line if ary[0][0] is upper-left corner
    #ary = numpy.flipup(ary)
    Ny, Nx = ary.shape
    item_length = Ny * Nx

    import csv
    lol = [lon.ravel(), lat.ravel(), ary.ravel()]
    with open(filename, 'wb') as test_file:
        file_writer = csv.writer(test_file)
        for i in range(item_length):
            file_writer.writerow([x[i] for x in lol])
    print "File written to: " + filename
Example #6
0
def writeTiff(ary,
              coord,
              filename='kgiAlos.tif',
              rescale=None,
              dataformat=gdal.GDT_Float64,
              lon=None,
              lat=None,
              nodata=None,
              grid=None,
              srs_proj4='+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'):
    '''writeTiff(ary, geoTransform, filename='kgiAlos.tif', rescale=None, format=gdal.GDT_Float64 ,lon=None, lat=None):
    ary: 2D array.
    geoTransform: [top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution]
    rescale: [min max]: If given rescale ary values between min and max.
    grid: Gridding (interpolation) method None, 'nearest', 'linear', or 'cubic'. Default None.  
    If lon lat is specified set coord to None
    
    '''

    if coord is None:
        import scipy
        import scipy.linalg
        s = [sk / 10 for sk in ary.shape]
        ary10 = ary[::s[0], ::s[1]]
        lon10 = lon[::s[0], ::s[1]]
        lat10 = lat[::s[0], ::s[1]]
        #P.figure()
        #P.scatter(lon10.ravel(), lat10.ravel(), 5, ary10.ravel(), edgecolors='none')
        A = N.ones([N.multiply(*ary10.shape), 3])
        line, pixel = N.meshgrid(N.r_[0:ary.shape[0]:s[0]],
                                 N.r_[0:ary.shape[1]:s[1]])
        A[:, 1] = pixel.ravel()
        A[:, 2] = line.ravel()
        xlon = N.dot(scipy.linalg.pinv(A), lon10.ravel())
        xlat = N.dot(scipy.linalg.pinv(A), lat10.ravel())
        ##check flip flop
        #if xlon[1]<0: #flip lr
        #    ary=N.fliplr(ary)
        #
        #if xlat[2]>0: #flip ud
        #    ary=N.flipud(ary)
        coord = [xlon[0], xlon[2], xlon[1], xlat[0], xlat[2], xlat[1]]
        print coord
        #x=lon[0,0]
        #y=lat[0,0]
        #dx=lon[0,1]-lon[0,0]
        #dy=lat[1,0]-lat[0,0]
        #xrot=0.
        #yrot=0.
        #coord=[x,dx, xrot, y,yrot, dy]

        if grid is not None:
            import scipy.interpolate
            LON, LAT = N.meshgrid(N.r_[lon.min():lon.max():abs(coord[1])],
                                  N.r_[lat.max():lat.min():-abs(coord[5])])
            #ary=P.griddata(lon.ravel(),lat.ravel(),ary.ravel(),LON,LAT);
            ary = scipy.interpolate.griddata(N.array(
                [lon.ravel(), lat.ravel()]).T,
                                             ary.ravel(), (LON, LAT),
                                             method=grid,
                                             fill_value=nodata)
            coord = [
                LON[0, 0],
                abs(coord[1]), 0, LAT[0, 0], 0, -abs(coord[5])
            ]
            print coord

    if rescale:
        import basic
        ary = basic.rescale(ary, rescale)

    # data exists in 'ary' with values range 0 - 255
    # Uncomment next line if ary[0][0] is upper-left corner
    #ary = numpy.flipup(ary)
    Ny, Nx = ary.shape
    driver = gdal.GetDriverByName("GTiff")
    ds = driver.Create(filename, Nx, Ny, 1, gdal.GDT_Float64)

    #ds.SetGeoTransform( ... ) # define GeoTransform tuple
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    ds.SetGeoTransform(coord)
    srs = osr.SpatialReference()
    if os.path.isfile(srs_proj4):
        srs.ImportFromWkt(open(srs_proj4).read())
    else:
        srs.ImportFromProj4(srs_proj4)

    ds.SetProjection(srs.ExportToWkt())
    if nodata is not None:
        ds.GetRasterBand(1).SetNoDataValue(nodata)
    ds.GetRasterBand(1).WriteArray(ary)
    ds = None
    print "File written to: " + filename