コード例 #1
0
def test_02_01_median():
    '''A median filter larger than the image = median of image'''
    np.random.seed(0)
    img = np.random.uniform(size=(9, 9))
    result = median_filter(img, 20, np.ones((9, 9), bool))
    np.testing.assert_equal(result[0, 0], np.median(img))
    assert (np.all(result == np.median(img)))
コード例 #2
0
def test_02_01_median():
    '''A median filter larger than the image = median of image'''
    np.random.seed(0)
    img = np.random.uniform(size=(9, 9))
    result = median_filter(img, 20, np.ones((9, 9), bool))
    np.testing.assert_equal(result[0, 0], np.median(img))
    assert (np.all(result == np.median(img)))
コード例 #3
0
def test_03_01_shape():
    '''Make sure the median filter is the expected octagonal shape'''

    radius = 5
    a_2 = int(radius / 2.414213)
    i, j = np.mgrid[-10:11, -10:11]
    octagon = np.ones((21, 21), bool)
    #
    # constrain the octagon mask to be the points that are on
    # the correct side of the 8 edges
    #
    octagon[i < -radius] = False
    octagon[i > radius] = False
    octagon[j < -radius] = False
    octagon[j > radius] = False
    octagon[i + j < -radius - a_2] = False
    octagon[j - i > radius + a_2] = False
    octagon[i + j > radius + a_2] = False
    octagon[i - j > radius + a_2] = False
    np.random.seed(0)
    img = np.random.uniform(size=(21, 21))
    result = median_filter(img, radius, np.ones((21, 21), bool))
    sorted = img[octagon]
    sorted.sort()
    min_acceptable = sorted[len(sorted) / 2 - 1]
    max_acceptable = sorted[len(sorted) / 2 + 1]
    assert (result[10, 10] >= min_acceptable)
    assert (result[10, 10] <= max_acceptable)
コード例 #4
0
def test_03_01_shape():
    '''Make sure the median filter is the expected octagonal shape'''

    radius = 5
    a_2 = int(radius / 2.414213)
    i, j = np.mgrid[-10:11, -10:11]
    octagon = np.ones((21, 21), bool)
    #
    # constrain the octagon mask to be the points that are on
    # the correct side of the 8 edges
    #
    octagon[i < -radius] = False
    octagon[i > radius] = False
    octagon[j < -radius] = False
    octagon[j > radius] = False
    octagon[i + j < -radius - a_2] = False
    octagon[j - i > radius + a_2] = False
    octagon[i + j > radius + a_2] = False
    octagon[i - j > radius + a_2] = False
    np.random.seed(0)
    img = np.random.uniform(size=(21, 21))
    result = median_filter(img, radius, np.ones((21, 21), bool))
    sorted = img[octagon]
    sorted.sort()
    min_acceptable = sorted[len(sorted) / 2 - 1]
    max_acceptable = sorted[len(sorted) / 2 + 1]
    assert (result[10, 10] >= min_acceptable)
    assert (result[10, 10] <= max_acceptable)
コード例 #5
0
def test_01_01_mask():
    '''The median filter, masking a single value'''
    img = np.zeros((10, 10))
    img[5, 5] = 1
    mask = np.ones((10, 10), bool)
    mask[5, 5] = False
    result = median_filter(img, 3, mask)
    assert (np.all(result[mask] == 0))
    np.testing.assert_equal(result[5, 5], 1)
コード例 #6
0
def test_01_01_mask():
    '''The median filter, masking a single value'''
    img = np.zeros((10, 10))
    img[5, 5] = 1
    mask = np.ones((10, 10), bool)
    mask[5, 5] = False
    result = median_filter(img, 3, mask)
    assert (np.all(result[mask] == 0))
    np.testing.assert_equal(result[5, 5], 1)
コード例 #7
0
def test_02_02_median_bigger():
    '''Use an image of more than 255 values to test approximation'''
    np.random.seed(0)
    img = np.random.uniform(size=(20, 20))
    result = median_filter(img, 40, np.ones((20, 20), bool))
    sorted = np.ravel(img)
    sorted.sort()
    min_acceptable = sorted[198]
    max_acceptable = sorted[202]
    assert (np.all(result >= min_acceptable))
    assert (np.all(result <= max_acceptable))
コード例 #8
0
def test_02_02_median_bigger():
    '''Use an image of more than 255 values to test approximation'''
    np.random.seed(0)
    img = np.random.uniform(size=(20, 20))
    result = median_filter(img, 40, np.ones((20, 20), bool))
    sorted = np.ravel(img)
    sorted.sort()
    min_acceptable = sorted[198]
    max_acceptable = sorted[202]
    assert (np.all(result >= min_acceptable))
    assert (np.all(result <= max_acceptable))
コード例 #9
0
def test_04_01_half_masked():
    '''Make sure that the median filter can handle large masked areas.'''
    img = np.ones((20, 20))
    mask = np.ones((20, 20), bool)
    mask[10:, :] = False
    img[~mask] = 2
    img[1, 1] = 0  # to prevent short circuit for uniform data.
    result = median_filter(img, 5, mask)
    # in partial coverage areas, the result should be only
    # from the masked pixels
    assert (np.all(result[:14, :] == 1))
    # in zero coverage areas, the result should be the lowest
    # value in the valid area
    assert (np.all(result[15:, :] == np.min(img[mask])))
コード例 #10
0
def test_04_01_half_masked():
    '''Make sure that the median filter can handle large masked areas.'''
    img = np.ones((20, 20))
    mask = np.ones((20, 20), bool)
    mask[10:, :] = False
    img[~ mask] = 2
    img[1, 1] = 0  # to prevent short circuit for uniform data.
    result = median_filter(img, 5, mask)
    # in partial coverage areas, the result should be only
    # from the masked pixels
    assert (np.all(result[:14, :] == 1))
    # in zero coverage areas, the result should be the lowest
    # value in the valid area
    assert (np.all(result[15:, :] == np.min(img[mask])))
コード例 #11
0
ファイル: DuPolfiguresGRL.py プロジェクト: lelou6666/PySOL
def main( argv=None ):

    # default values
    pn = '/media/data/data/OTHER/RS2 Agulhas and Lion/RS2_FQA_1xQGSS20101218_173930_00000005/'
    xOff=0
    yOff=0
    xS=None
    yS=None
    xBufScale=None
    yBufScale=None
    s = 'abs'

    if argv is None:
        argv = sys.argv

    if argv is None:
        print ( "Please specify the path to the RS2 folder! \n" + \
                "See USAGE for more details \n")
        return Usage()

    # Parse arguments
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["pn=","xoff="])
    except getopt.GetoptError:
        print 'readRS2.py -pn <inputfile> ...'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'readRS2.py -pn <inputfile> ...'
            sys.exit()
        elif opt in ("-pn", "--pn"):
            pn = arg
        elif opt in ("-xoff", "--xoff"):
            xOff = arg
        elif opt in ("-yoff", "--yoff"):
            yOff = arg
        elif opt in ("-xS", "--xS"):
            xS = arg
        elif opt in ("-yS", "--yS"):
            yS = arg
        elif opt in ("-xScale", "--xScale"):
            xBufScale = arg
        elif opt in ("-yScale", "--yScale"):
            yBufScale = arg

    print "Path to the RS2 file:\n", pn

    if core_ct < 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calib = calibRS2(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, 'sigma0')
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calib.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calib.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calib.speckle_filter('wiener', 7)
        print 'Serial: time elapsed:', time() - currtime
    elif core_ct >= 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calibPar = calibRS2par(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, s)
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calibPar.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calibPar.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calibPar.speckle_filter('wiener', 7)
        print 'Parallel: time elapsed: %f' % ( time() - currtime )
        # export to geotiff
#        calibPar.save_tiff()

    print "Some Sigma calculations..."

    SigmaHHwnr = calibPar.SigmaHHwnr
    SigmaVVwnr = calibPar.SigmaVVwnr
#    SigmaHVwnr = calibPar.SigmaHVwnr

    # Free up some memory
    del calibPar.SigmaHHwnr, calibPar.SigmaVVwnr, calibPar.SigmaHVwnr

#    # Calculate some wind
#    # testing that with sar=-0.387 wind speed is 10m/s
#    w = rcs2wind(sar=-0.387*ones((1,1)), cmdv=4, windir=0, theta=20*ones((1,1)))
#    print "Testing CMOD4 passed, Wind =", w
#
#    sar=10*log10(SigmaVVwnr[::10,::10])
##    sar=10*log10(SigmaVVwnr)
#    w = rcs2wind(sar, cmdv=4, windir=130, theta=33*ones(sar.shape))
#    print "Mean CMOD4 Wind =", w.mean()

    # calculate the conjugate
    SigmaVVConjHH = calibPar.S_VV*conj(calibPar.S_HH)
    SigmaVVConjHHWnr = wiener(SigmaVVConjHH, mysize=(7,7), noise=None)
    # all sigmas in linear units
    SigmaVVConjHHdelta = SigmaVVConjHHWnr/(SigmaVVwnr - SigmaHHwnr)

#    # Check that imagenary part is much less then the real one
#    SigmaVVConjHHr = real(SigmaVVConjHH)
#    SigmaVVConjHHi = imag(SigmaVVConjHH)
#    SigmaVVConjHHr.mean()
#    SigmaVVConjHHi.mean()

    # Free up some memory
    del SigmaVVConjHH, calibPar.S_HH, calibPar.S_VV

    # 2. Find Poolarization ratio PR in dB and delta - linear
    # delta - is a Bragg component, which describes wind field impact
    # PR = 10*log10(SigmaHHwnr) - 10*log10(SigmaVVwnr)
#    # PR must not be > 0, be careful with masking
    #P[P>0] = 0
    PR = SigmaHHwnr/SigmaVVwnr
    delta = SigmaVVwnr - SigmaHHwnr



#    # Masking Land from HV polarization
#    maskedLand = SigmaHVwnr>0.003

    # 3. Linear fit of Sigma and delta: Sigma = A*delta
#    A = sum(SigmaVVwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
#    B = sum(SigmaHHwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
    # imposing from theory
    A = linspace(2.3,1.8,IncidenceAngle.size) # dependence on inc angle
    A = tile(A, (line[-1,0]+1, 1))

    # 4. Calculate SigmaVVwb = SigmaVVwb === SigmaHHwb
    # substracting wind field variability contribution, the rest is impact of
    # current and film on the image
    SigmaWb = SigmaVVwnr - ( A*delta )

    # Checking that SigmaWb from VV and HH are the same
    # SigmaVVwb = SigmaVVwnr - ( A*delta )
    # SigmaHHwb = SigmaHHwnr - ( B*delta )
    # SigmaWb = SigmaVVwb
    # mean(SigmaHHwb(:)./SigmaVVwb(:))
    # clear SigmaVVwb SigmaHHwb

    # Cropping the oil slicks

##    проверить почему переворот изображения!!!
#    from imcrop import imzoom
#    print ( "Cropping...")
#    plt.figure()
#    plt.imshow(SigmaWb)
#    plt.clim(0,0.03)
#    plt.gray()
#    plt.show()
#    pts = imzoom()

    ptsCropSouth = array([[ 3200, 4550],
                          [ 3800, 5100]])
    oilCropSouth = imcrop(ptsCropSouth, delta)
    ptsCropNorth = array([[ 3400, 0],
                          [ 4900,  1650]])
    oilCropNorth = imcrop(ptsCropNorth, delta)

    # reduce the speckle noise
    oilN = wiener(oilCropNorth, mysize=(3,3), noise=None)
    oilS = wiener(oilCropSouth, mysize=(3,3), noise=None)

    # use median filter to smooth
    oilN = median_filter(oilN, radius=37)
    oilS = median_filter(oilS, radius=37)

    # find the global threshold
    global_threshN = threshold_otsu(oilN)
    global_threshS = threshold_otsu(oilS)

    # create a binary mask
    markersN = ones(oilN.shape, dtype=uint)
    markersS = ones(oilS.shape, dtype=uint)
    markersN[oilN < global_threshN*0.84] = 0
    markersS[oilS < global_threshS*0.84] = 0

    # Find the relation of PR in/out-side the Slicks
    oilCropNorthPR = imcrop(ptsCropNorth, PR)
    oilCropPN = oilCropNorthPR[markersN==0].mean()/oilCropNorthPR[markersS==1].mean()

    oilCropSouthP = imcrop(ptsCropSouth, PR)
    oilCropPS = oilCropSouthP[markersS==0].mean()/oilCropSouthP[markersS==1].mean()

    # Checking that calculations are OK
    oilCropNorthKVV = imcrop(ptsCropNorth, SigmaVVwnr)
    KVV = oilCropNorthKVV[markersN==0].mean()/oilCropNorthKVV[markersN==1].mean()
    oilCropNorthKHH = imcrop(ptsCropNorth, SigmaHHwnr)
    KHH = oilCropNorthKHH[markersN==0].mean()/oilCropNorthKHH[markersN==1].mean()
    PSlick = KHH/KVV*oilCropNorthKHH[markersN==1].mean()/oilCropNorthKVV[markersN==1].mean()

    print "Polarization ratio Out/In-side Slick = \
        \n %0.2f for Northern \n %0.2f for Southern" \
        %(1/oilCropPN, 1/oilCropPS)

    oilCropNorthVV = imcrop(ptsCropNorth, SigmaVVwnr)
    oilCropNorthDelta = imcrop(ptsCropNorth, delta)
    oilCropNorthSigmaWb = imcrop(ptsCropNorth, SigmaWb)

    print ( "Plotting on a map... \nUsing default NSPER Basemap \n")

    # setup nsper basemap
    # Lat/Lon coords of image corners
    ll_lat = lat.min()
    ur_lat = lat.max()
    ll_lon = lon.min()
    ur_lon = lon.max()
    cent_lat = lat.mean()
    cent_lon = lon.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='f', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

#    m = Basemap(llcrnrlat=30, urcrnrlat=50,\
#                llcrnrlon=1, urcrnrlon=20, \
#                resolution='l', projection='nsper', \
#                satellite_height=798000, \
#                lat_0=cent_lat,lon_0=cent_lon)

    print ( "Plotting figures... \n")

    scale = 8 # setting scale factor to resize in 1/scale times
    label1 = 'Sigma VV [dB]'
    label2 = 'Sigma HH [dB]'
    label11 = 'Sigma VV [linear units]'
    label22 = 'Sigma HH [linear units]'
    label3 = 'PR [dB]'
    label33 = 'PR [linear units]'
    label4 = 'PD [linear units]'
    label5 = 'Wb contribution [linear units]'
    label6 = 'SigmaVVConjHH [linear units]'
    label7 = 'SigmaVVConjHHdelta [linear units]'

#    label8 = 'Wind CMOD4 [m/s]'

#    import plotRS2
#    reload(plotRS2)
#    from plotRS2 import plotRS2

#    import mpl_util
#    reload(mpl_util)
#
#    import gmtColormap
#    reload(gmtColormap)
#
#    import createMapsEtopo1
#    reload(createMapsEtopo1)
#    from createMapsEtopo1 import makeMap
#
#    import g1sst
#    reload(g1sst)
#    from g1sst import g1sst

#    plotRS2(10*log10(SigmaVVwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label1)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label1, contour='land')
#    plt.close('all')
#
#    plotRS2(10*log10(SigmaHHwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label2)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label2, contour='land')
#    plt.close('all')
#    plotRS2(PR, lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-2.7,0), label=label3)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label3, contour='land')
#    plt.close('all')

    # Coords to plot Figure number
    x, y = m(3.15, 42.15)

    # Figure 1 a - VV
    plotRS2(SigmaVVwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.05), label=label11)
    plt.text(x,y,"a",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label11, contour='land')
    plt.close('all')
    a = label11.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1a_.tiff")
    system("convert -compress lzw /home/mag/Figure1a_.tiff /home/mag/Figure1a_.tiff")

    # Figure 1 b - HH
    plotRS2(SigmaHHwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.05), label=label22)
    plt.text(x,y,"b",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label22, contour='land')
    plt.close('all')
    a = label22.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1b_.tiff")
    system("convert -compress lzw /home/mag/Figure1b_.tiff /home/mag/Figure1b_.tiff")

    # Figure 1 c - polarization ratio (PR) (always<1)
    plotRS2(PR, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0.6,0.9), label=label33)
    plt.text(x,y,"c",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label3, contour='land')
    plt.close('all')
    a = label33.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1c_.tiff")
    system("convert -compress lzw /home/mag/Figure1c_.tiff /home/mag/Figure1c_.tiff")

    # Figure 1 d - polarization difference (PD) (always>0)
    plotRS2(delta, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.02), label=label4)
    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label4, contour='land')
    plt.close('all')
    a = label4.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1d_.tiff")
    system("convert -compress lzw /home/mag/Figure1d_.tiff /home/mag/Figure1d_.tiff")


    # Figure 4 - wave breaking contribution
    plotRS2(SigmaWb, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.03), label=label5)
#    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label5, contour='land')
    plt.close('all')
    a = label5.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure4.tiff")
    system("convert -compress lzw /home/mag/Figure4.tiff /home/mag/Figure4.tiff")


    # Figure 3
    # Plot cropped Current
    ptsCropCurrent = array([[ 970, 3061], [2756, 5401]])
    CurrentVV = imcrop(ptsCropCurrent, SigmaVVwnr)
    CurrentPD = imcrop(ptsCropCurrent, delta)
    CurrentPR = imcrop(ptsCropCurrent, PR)
    CurrentWb = imcrop(ptsCropCurrent, SigmaWb)

    # Transect Current Front
#    pts = array([[1400, 4300], [2100, 3600]])
#    PDtrans = transect.transect(delta, pts, 30)[1]
#    PRtrans = transect.transect(PR, pts, 30)[1]
#    VVtrans = transect.transect(SigmaVVwnr, pts, 30)[1]
#    SigmaWbtrans = transect.transect(SigmaWb, pts, 30)[1]

#    Пока нет возможности сделать преобразование коорлинат, чтобы при помощи
#    imcrop находить координаты сечения исходного изображения в вырезанном.
#    Поэтому пока делаем сечение в вырезанной области, а в функцию plotTrnsImage
#    передаём исходные изображения и координаты для вырезания.
    pts = array([[ 650, 1700], [1230,  1000]])
    PDtrans = transect.transect(CurrentPD, pts, 30)[1]
    PRtrans = transect.transect(CurrentPR, pts, 30)[1]
    VVtrans = transect.transect(CurrentVV, pts, 30)[1]
    SigmaWbtrans = transect.transect(CurrentWb, pts, 30)[1]

    # setup nsper basemap
    # Lat/Lon coords of image corners
    lat_new, lon_new = intCrpLL(lat, lon, pixel, line, scale=1, ptsCrop=ptsCropCurrent)
    ll_lat = lat_new.min()
    ur_lat = lat_new.max()
    ll_lon = lon_new.min()
    ur_lon = lon_new.max()
    cent_lat = lat_new.mean()
    cent_lon = lon_new.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='c', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

    # Get the length of the transect. Input coords in (row,col)
    trnsLength = distancelib.getDistancePx([pts[0,1], pts[0,0]], [pts[1,1], pts[1,0]], lat_new, lon_new, CurrentVV)
    dist = linspace(0, trnsLength, len(VVtrans))
    
    print "Exporting transect to .mat file"
    pn = '/home/mag/Documents/MATLAB/Leon_Agulhas_RS2/'
    expFn = 'CurrentFrontTrns/CurrentFrontTrns.mat'
    if not path.isfile(pn + expFn):
        print "Exporting to:\n" , pn + expFn
        savemat(pn + expFn, mdict={ \
                'dist':dist, \
                'VVtrans':VVtrans, \
                'PRtrans':PRtrans, \
                'PDtrans':PDtrans, \
                'Wbtrans':SigmaWbtrans, \
                }, do_compression=False)

    # Figure 3 a - VVtrans Image
    transect.plotTrnsImage(VVtrans, pts, lat, lon, SigmaVVwnr, pixel, line, \
                           pn='/home/mag/', \
                           label=label11, \
                           clm=(0.01,0.05), ptsCrop=ptsCropCurrent, m=m, scale=1)
    plt.close('all')
    transect.plotTrns(VVtrans, pts, lat_new, lon_new, CurrentVV, \
                      pn='/home/mag/', \
                      label=label11)
    # Figure 3 b - VVtrans
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3a.tiff")
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-trns.tiff /home/mag/Figure3b.tiff")

    # Figure 3 c - PRtrans Image
    transect.plotTrnsImage(PRtrans, pts, lat, lon, PR, pixel, line, \
                           pn='/home/mag/', \
                           label=label33, \
                           clm=(0.65,0.9), ptsCrop=ptsCropCurrent, m=m, scale=1)
    plt.close('all')
    # Figure 3 d - PRtrans
    transect.plotTrns(PRtrans, pts, lat_new, lon_new, CurrentPR, \
                      pn='/home/mag/', \
                      label=label33)
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3c.tiff")
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-trns.tiff /home/mag/Figure3d.tiff")

    # Figure 3 e - PDtrans Image
    transect.plotTrnsImage(PDtrans, pts, lat, lon, delta, pixel, line, \
                           pn='/home/mag/', \
                           label=label4, \
                           clm=(0.,0.02), ptsCrop=ptsCropCurrent, m=m, scale=1)
    plt.close('all')
    # Figure 3 f - PRtrans
    transect.plotTrns(PDtrans, pts, lat_new, lon_new, CurrentPD, \
                      pn='/home/mag/', \
                      label=label4)
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3e.tiff")
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-trns.tiff /home/mag/Figure3f.tiff")

    # Figure 3 g - PDtrans Image
    transect.plotTrnsImage(SigmaWbtrans, pts, lat, lon, SigmaWb, pixel, line, \
                           pn='/home/mag/', \
                           label=label5, \
                           clm=(0.,0.03), ptsCrop=ptsCropCurrent, m=m, scale=1)
    plt.close('all')
    # Figure 3 h - PRtrans
    transect.plotTrns(SigmaWbtrans, pts, lat_new, lon_new, CurrentWb, \
                      pn='/home/mag/', \
                      label=label5)
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3g.tiff")
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-trns.tiff /home/mag/Figure3h.tiff")


    # Figure Transects as subplot
    plt.figure(figsize=(7, 5))
    plt.subplot(411)
    plt.plot(dist, VVtrans)
    plt.text(dist[15],(VVtrans.max()+VVtrans.min())/1.51, \
             label11, \
             bbox=dict(facecolor='w'),stretch='expanded',fontsize=27)
    plt.grid()
    plt.subplot(412)
    plt.plot(dist, PRtrans)
    plt.text(dist[15],(PRtrans.max()+PRtrans.min())/1.77, \
             label33, \
             bbox=dict(facecolor='w'),stretch='expanded',fontsize=27)
    plt.grid()    
    plt.subplot(413)
    plt.plot(dist, PDtrans)
    plt.text(dist[15],(PDtrans.max()+PDtrans.min())/1.34, \
             label4, \
             bbox=dict(facecolor='w'),stretch='expanded',fontsize=27)
    plt.grid()
    plt.subplot(414)
    plt.text(dist[15],(SigmaWbtrans.max()+SigmaWbtrans.min())/1.27, \
             label5, \
             bbox=dict(facecolor='w'),stretch='expanded',fontsize=27)
    plt.plot(dist, SigmaWbtrans)
    plt.grid()    
    plt.xlabel('Distance [km]')


#    
#    
#    plt.title(label)
#    plt.axis('tight')
#    plt.text(dist[15],(trn.max()+trn.min())/2,"A",bbox=dict(facecolor='w', alpha=0.7),stretch='expanded',fontsize=27)
#    plt.text(dist[-55],(trn.max()+trn.min())/2,"B",bbox=dict(facecolor='w', alpha=0.7),stretch='expanded',fontsize=27)
#    if fign is not None:
#        plt.text(dist.max()*0.9,trn.max()-(trn.max()-trn.min())*0.1,fign,bbox=dict(facecolor='w', alpha=1),stretch='expanded',fontsize=27)
##    mng = plt.get_current_fig_manager()
##    mng.resize(1920,1080)
#    plt.draw()
#    a = label.split(' ')[0] # split the name if it has spaces
#    plt.savefig(pn+a+'-trns.tiff', facecolor='w', edgecolor='w', \
#                 dpi=300, bbox_inches="tight", pad_inches=0.1)
#
#
#








    # Figure 5
    # Plot cropped Northern Oil Spill
    lat_new, lon_new = intCrpLL(lat, lon, pixel, line, scale=1, ptsCrop=ptsCropNorth)
    ll_lat = lat_new.min()
    ur_lat = lat_new.max()
    ll_lon = lon_new.min()
    ur_lon = lon_new.max()
    cent_lat = lat_new.mean()
    cent_lon = lon_new.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='c', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

    # Transect North Oil Slick
    pts = array([[613, 851], [833, 1033]])

    # [1] returns only Mean Transect
    PDtrans = transect.transect(oilCropNorthDelta, pts, 30)[1]
    PRtrans = transect.transect(oilCropNorthPR, pts, 30)[1]
    VVtrans = transect.transect(oilCropNorthVV, pts, 30)[1]
    SigmaWbtrans = transect.transect(oilCropNorthSigmaWb, pts, 30)[1]

    # Get the length of the transect. Input coords in (row,col)
    trnsLength = distancelib.getDistancePx([pts[0,1], pts[0,0]], [pts[1,1], pts[1,0]], lat_new, lon_new, oilCropNorthVV)
    dist = linspace(0, trnsLength, len(VVtrans))
    
    print "Exporting transect to .mat file"
    pn = '/home/mag/Documents/MATLAB/Leon_Agulhas_RS2/'
    expFn = 'OilSlickTrns/OilSlickTrns.mat'
    if not path.isfile(pn + expFn):
        print "Exporting to:\n" , pn + expFn
        savemat(pn + expFn, mdict={ \
                'dist':dist, \
                'VVtrans':VVtrans, \
                'PRtrans':PRtrans, \
                'PDtrans':PDtrans, \
                'Wbtrans':SigmaWbtrans, \
                }, do_compression=False)

    # Figure 5 a - VVtrans Image
    transect.plotTrnsImage(VVtrans, pts, lat, lon, SigmaVVwnr, pixel, line, \
                           pn='/home/mag/', \
                           label=label11, \
                           clm=(0.01,0.05), ptsCrop=ptsCropNorth, m=m, scale=1, fign='a')
    plt.close('all')
    # Figure 5 b - VVtrans
    transect.plotTrns(VVtrans, pts, lat_new, lon_new, oilCropNorthVV, \
                      pn='/home/mag/', \
                      label=label11, fign='b')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5a.tiff")
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-trns.tiff /home/mag/Figure5b.tiff")

    # Figure 5 c - PRtrans Image
    transect.plotTrnsImage(PRtrans, pts, lat, lon, PR, pixel, line, \
                           pn='/home/mag/', \
                           label=label33, \
                           clm=(0.65,0.9), ptsCrop=ptsCropNorth, m=m, scale=1)
    plt.close('all')
    # Figure 5 d - PRtrans
    transect.plotTrns(PRtrans, pts, lat_new, lon_new, oilCropNorthPR, \
                      pn='/home/mag/', \
                      label=label33)
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5c.tiff")
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-trns.tiff /home/mag/Figure5d.tiff")

    # Figure 5 e - PDtrans Image
    transect.plotTrnsImage(PDtrans, pts, lat, lon, delta, pixel, line, \
                           pn='/home/mag/', \
                           label=label4, \
                           clm=(0.,0.02), ptsCrop=ptsCropNorth, m=m, scale=1)
    plt.close('all')
    # Figure 5 f - PRtrans
    transect.plotTrns(PDtrans, pts, lat_new, lon_new, oilCropNorthDelta, \
                      pn='/home/mag/', \
                      label=label4)
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5e.tiff")
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-trns.tiff /home/mag/Figure5f.tiff")

    # Figure 5 g - PDtrans Image
    transect.plotTrnsImage(SigmaWbtrans, pts, lat, lon, SigmaWb, pixel, line, \
                           pn='/home/mag/', \
                           label=label5, \
                           clm=(0.,0.03), ptsCrop=ptsCropNorth, m=m, scale=1,)
    plt.close('all')
    # Figure 5 h - PRtrans
    transect.plotTrns(SigmaWbtrans, pts, lat_new, lon_new, oilCropNorthSigmaWb, \
                      pn='/home/mag/', \
                      label=label5)
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5g.tiff")
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-trns.tiff /home/mag/Figure5h.tiff")

    # Clean up
    system("rm " + "/home/mag/*trns.tiff")
コード例 #12
0
def test_00_02_all_but_one_masked():
    mask = np.zeros((10, 10), bool)
    mask[5, 5] = True
    median_filter(np.zeros((10, 10)), 3, mask)
コード例 #13
0
def test_wrong_shape():
    img = np.empty((10, 10, 3))
    median_filter(img)
コード例 #14
0
def test_00_01_all_masked():
    '''Test a completely masked image

    Regression test of IMG-1029'''
    result = median_filter(np.zeros((10, 10)), 3, np.zeros((10, 10), bool))
    assert (np.all(result == 0))
コード例 #15
0
def test_insufficient_size():
    img = (np.random.random((20, 20)) * 255).astype(np.uint8)
    median_filter(img, radius=1)
コード例 #16
0
def test_00_02_all_but_one_masked():
    mask = np.zeros((10, 10), bool)
    mask[5, 5] = True
    median_filter(np.zeros((10, 10)), 3, mask)
コード例 #17
0
def getNeighbourKernel(segmentKernelSize, rotation, springCost, rotationCost):

    pass


def getNeighbourSuggestion(modelList, I):

    pass


gs = np.load("dev/gs.npy")

#Edgekernel
K = np.ones((4, 6))
K[:2] = -1

#Segment kernel
R = makeSegmentKernel((28, 61), edge=2)

#Vertical features
V = np.abs(ndimage.convolve(gs.astype(np.float), K.T))
V = ndimage.binary_erosion(
    np.logical_and(V < np.mean(V) * 15, V > np.mean(V) * 1.5))

#Horizontal features
H = filter.median_filter(
    ndimage.binary_erosion(ndimage.convolve(gs.astype(np.float), K) > 0), 3)

#Composite features
D = ndimage.convolve((V + H).astype(np.float), R)
コード例 #18
0
ファイル: edgeCanny.py プロジェクト: whigg/PySOL
from skimage.filter import threshold_otsu
from skimage.filter import median_filter

ptsCropSouth = array([[3000, 4650], [3700, 5200]])
oilCropSouth = imcrop(ptsCropSouth, delta)
ptsCropNorth = array([[3400, 0], [4900, 1650]])
oilCropNorth = imcrop(ptsCropNorth, delta)

image = oilCropNorth

# reduce the speckle noise
image = wiener(image, mysize=(3, 3), noise=None)

# use median filter to smooth
image = median_filter(image, radius=37)

# find the global threshold
global_thresh = threshold_otsu(image)

# create a binary mask
markers = ones(image.shape, dtype=uint)
markers[image < global_thresh * 0.84] = 0

oilCropNorthMeanP = P[markers == 1]
oilCropNorthMeanP = oilCropNorthMeanP.mean()

## display results
#plt.figure()
#plt.subplot(131)
#plt.imshow(image, cmap=plt.cm.gray)
コード例 #19
0
ファイル: edgeCanny.py プロジェクト: lelou6666/PySOL
from skimage.filter import median_filter

ptsCropSouth = array([[ 3000, 4650],
                      [ 3700, 5200]])
oilCropSouth = imcrop(ptsCropSouth, delta)
ptsCropNorth = array([[ 3400, 0],
                      [ 4900,  1650]])
oilCropNorth = imcrop(ptsCropNorth, delta)

image = oilCropNorth

# reduce the speckle noise
image = wiener(image, mysize=(3,3), noise=None)

# use median filter to smooth
image = median_filter(image, radius=37)

# find the global threshold
global_thresh = threshold_otsu(image)

# create a binary mask
markers = ones(image.shape, dtype=uint)
markers[image < global_thresh*0.84] = 0

oilCropNorthMeanP = P[markers==1]
oilCropNorthMeanP = oilCropNorthMeanP.mean()

## display results
#plt.figure()
#plt.subplot(131)
#plt.imshow(image, cmap=plt.cm.gray)
コード例 #20
0
"""
This example compares several denoising filters available in scikit-image:
a Gaussian filter, a median filter, and total variation denoising.
"""

import matplotlib.pyplot as plt
from skimage import data
from skimage import filter
from scipy import ndimage

coins = data.coins()
gaussian_filter_coins = ndimage.gaussian_filter(coins, sigma=2)
med_filter_coins = filter.median_filter(coins)
tv_filter_coins = filter.tv_denoise(coins, weight=0.1)

plt.figure(figsize=(16, 4))
plt.subplot(141)
plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Image")
plt.subplot(142)
plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Gaussian filter")
plt.subplot(143)
plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Median filter")
plt.subplot(144)
plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
コード例 #21
0
def test_default_values():
    img = (np.random.random((20, 20)) * 255).astype(np.uint8)
    mask = np.ones((20, 20), dtype=np.uint8)
    result1 = median_filter(img, radius=2, mask=mask, percent=50)
    result2 = median_filter(img)
    np.testing.assert_array_equal(result1, result2)
コード例 #22
0
def test_insufficient_size():
    img = (np.random.random((20, 20)) * 255).astype(np.uint8)
    median_filter(img, radius=1)
コード例 #23
0
def test_00_01_all_masked():
    '''Test a completely masked image

    Regression test of IMG-1029'''
    result = median_filter(np.zeros((10, 10)), 3, np.zeros((10, 10), bool))
    assert (np.all(result == 0))
コード例 #24
0
def main( argv=None ):

    # default values
    pn = '/media/data/data/OTHER/RS2 Agulhas and Lion/RS2_FQA_1xQGSS20101218_173930_00000005/'
    xOff=0
    yOff=0
    xS=None
    yS=None
    xBufScale=None
    yBufScale=None
    s = 'abs'

    if argv is None:
        argv = sys.argv

    if argv is None:
        print ( "Please specify the path to the RS2 folder! \n" + \
                "See USAGE for more details \n")
        return Usage()

    # Parse arguments
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["pn=","xoff="])
    except getopt.GetoptError:
        print 'readRS2.py -pn <inputfile> ...'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'readRS2.py -pn <inputfile> ...'
            sys.exit()
        elif opt in ("-pn", "--pn"):
            pn = arg
        elif opt in ("-xoff", "--xoff"):
            xOff = arg
        elif opt in ("-yoff", "--yoff"):
            yOff = arg
        elif opt in ("-xS", "--xS"):
            xS = arg
        elif opt in ("-yS", "--yS"):
            yS = arg
        elif opt in ("-xScale", "--xScale"):
            xBufScale = arg
        elif opt in ("-yScale", "--yScale"):
            yBufScale = arg

    print "Path to the RS2 file:\n", pn

    if core_ct < 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calib = calibRS2(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, 'sigma0')
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calib.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calib.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calib.speckle_filter('wiener', 7)
        print 'Serial: time elapsed:', time() - currtime
    elif core_ct >= 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calibPar = calibRS2par(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, s)
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calibPar.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calibPar.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calibPar.speckle_filter('wiener', 7)
        print 'Parallel: time elapsed: %f' % ( time() - currtime )
        # export to geotiff
#        calibPar.save_tiff()

    print "Some Sigma calculations..."

    SigmaHHwnr = calibPar.SigmaHHwnr
    SigmaVVwnr = calibPar.SigmaVVwnr
#    SigmaHVwnr = calibPar.SigmaHVwnr

    # Free up some memory
    del calibPar.SigmaHHwnr, calibPar.SigmaVVwnr, calibPar.SigmaHVwnr

#    # Calculate some wind
#    # testing that with sar=-0.387 wind speed is 10m/s
#    w = rcs2wind(sar=-0.387*ones((1,1)), cmdv=4, windir=0, theta=20*ones((1,1)))
#    print "Testing CMOD4 passed, Wind =", w
#
#    sar=10*log10(SigmaVVwnr[::10,::10])
##    sar=10*log10(SigmaVVwnr)
#    w = rcs2wind(sar, cmdv=4, windir=130, theta=33*ones(sar.shape))
#    print "Mean CMOD4 Wind =", w.mean()

    # calculate the conjugate
    SigmaVVConjHH = calibPar.S_VV*conj(calibPar.S_HH)
    SigmaVVConjHHWnr = wiener(SigmaVVConjHH, mysize=(7,7), noise=None)
    # all sigmas in linear units
    SigmaVVConjHHdelta = SigmaVVConjHHWnr/(SigmaVVwnr - SigmaHHwnr)

#    # Check that imagenary part is much less then the real one
#    SigmaVVConjHHr = real(SigmaVVConjHH)
#    SigmaVVConjHHi = imag(SigmaVVConjHH)
#    SigmaVVConjHHr.mean()
#    SigmaVVConjHHi.mean()

    # Free up some memory
    del SigmaVVConjHH, calibPar.S_HH, calibPar.S_VV

    # 2. Find Poolarization ratio PR in dB and delta - linear
    # delta - is a Bragg component, which describes wind field impact
    # PR = 10*log10(SigmaHHwnr) - 10*log10(SigmaVVwnr)
#    # PR must not be > 0, be careful with masking
    #P[P>0] = 0
    PR = SigmaHHwnr/SigmaVVwnr
    delta = SigmaVVwnr - SigmaHHwnr



#    # Masking Land from HV polarization
#    maskedLand = SigmaHVwnr>0.003

    # 3. Linear fit of Sigma and delta: Sigma = A*delta
#    A = sum(SigmaVVwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
#    B = sum(SigmaHHwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
    # imposing from theory
    A = linspace(2.3,1.8,IncidenceAngle.size) # dependence on inc angle
    A = tile(A, (line[-1,0]+1, 1))

    # 4. Calculate SigmaVVwb = SigmaVVwb === SigmaHHwb
    # substracting wind field variability contribution, the rest is impact of
    # current and film on the image
    SigmaWb = SigmaVVwnr - ( A*delta )

    # Checking that SigmaWb from VV and HH are the same
    # SigmaVVwb = SigmaVVwnr - ( A*delta )
    # SigmaHHwb = SigmaHHwnr - ( B*delta )
    # SigmaWb = SigmaVVwb
    # mean(SigmaHHwb(:)./SigmaVVwb(:))
    # clear SigmaVVwb SigmaHHwb

    # Cropping the oil slicks

##    проверить почему переворот изображения!!!
#    from imcrop import imzoom
#    print ( "Cropping...")
#    plt.figure()
#    plt.imshow(SigmaWb)
#    plt.clim(0,0.03)
#    plt.gray()
#    plt.show()
#    pts = imzoom()

    ptsCropSouth = array([[ 3200, 4550],
                          [ 3800, 5100]])
    oilCropSouth = imcrop(ptsCropSouth, delta)
    ptsCropNorth = array([[ 3400, 0],
                          [ 4900,  1650]])
    oilCropNorth = imcrop(ptsCropNorth, delta)

    # reduce the speckle noise
    oilN = wiener(oilCropNorth, mysize=(3,3), noise=None)
    oilS = wiener(oilCropSouth, mysize=(3,3), noise=None)

    # use median filter to smooth
    oilN = median_filter(oilN, radius=37)
    oilS = median_filter(oilS, radius=37)

    # find the global threshold
    global_threshN = threshold_otsu(oilN)
    global_threshS = threshold_otsu(oilS)

    # create a binary mask
    markersN = ones(oilN.shape, dtype=uint)
    markersS = ones(oilS.shape, dtype=uint)
    markersN[oilN < global_threshN*0.84] = 0
    markersS[oilS < global_threshS*0.84] = 0

    # Find the relation of PR in/out-side the Slicks
    oilCropNorthPR = imcrop(ptsCropNorth, PR)
    oilCropPN = oilCropNorthPR[markersN==0].mean()/oilCropNorthPR[markersS==1].mean()

    oilCropSouthP = imcrop(ptsCropSouth, PR)
    oilCropPS = oilCropSouthP[markersS==0].mean()/oilCropSouthP[markersS==1].mean()

    # Checking that calculations are OK
    oilCropNorthKVV = imcrop(ptsCropNorth, SigmaVVwnr)
    KVV = oilCropNorthKVV[markersN==0].mean()/oilCropNorthKVV[markersN==1].mean()
    oilCropNorthKHH = imcrop(ptsCropNorth, SigmaHHwnr)
    KHH = oilCropNorthKHH[markersN==0].mean()/oilCropNorthKHH[markersN==1].mean()
    PSlick = KHH/KVV*oilCropNorthKHH[markersN==1].mean()/oilCropNorthKVV[markersN==1].mean()

    print "Polarization ratio Out/In-side Slick = \
        \n %0.2f for Northern \n %0.2f for Southern" \
        %(1/oilCropPN, 1/oilCropPS)

    oilCropNorthVV = imcrop(ptsCropNorth, SigmaVVwnr)
    oilCropNorthDelta = imcrop(ptsCropNorth, delta)
    oilCropNorthSigmaWb = imcrop(ptsCropNorth, SigmaWb)

    print ( "Plotting on a map... \nUsing default NSPER Basemap \n")

    # setup nsper basemap
    # Lat/Lon coords of image corners
    ll_lat = lat.min()
    ur_lat = lat.max()
    ll_lon = lon.min()
    ur_lon = lon.max()
    cent_lat = lat.mean()
    cent_lon = lon.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='f', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

#    m = Basemap(llcrnrlat=30, urcrnrlat=50,\
#                llcrnrlon=1, urcrnrlon=20, \
#                resolution='l', projection='nsper', \
#                satellite_height=798000, \
#                lat_0=cent_lat,lon_0=cent_lon)

    print ( "Plotting figures... \n")

    scale = 8 # setting scale factor to resize in 1/scale times
    label1 = 'Sigma VV [dB]'
    label2 = 'Sigma HH [dB]'
    label11 = 'Sigma VV [linear units]'
    label22 = 'Sigma HH [linear units]'
    label3 = 'PR [dB]'
    label33 = 'PR [linear units]'
    label4 = 'PD [linear units]'
    label5 = 'Wb contribution [linear units]'
    label6 = 'SigmaVVConjHH [linear units]'
    label7 = 'SigmaVVConjHHdelta [linear units]'

#    label8 = 'Wind CMOD4 [m/s]'

#    import plotRS2
#    reload(plotRS2)
#    from plotRS2 import plotRS2

#    import mpl_util
#    reload(mpl_util)
#
#    import gmtColormap
#    reload(gmtColormap)
#
#    import createMapsEtopo1
#    reload(createMapsEtopo1)
#    from createMapsEtopo1 import makeMap
#
#    import g1sst
#    reload(g1sst)
#    from g1sst import g1sst

#    plotRS2(10*log10(SigmaVVwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label1)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label1, contour='land')
#    plt.close('all')
#
#    plotRS2(10*log10(SigmaHHwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label2)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label2, contour='land')
#    plt.close('all')
#    plotRS2(PR, lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-2.7,0), label=label3)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label3, contour='land')
#    plt.close('all')

    # Coords to plot Figure number
    x, y = m(3.15, 42.15)

    # Figure 1 a - VV
    plotRS2(SigmaVVwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.05), label=label11)
    plt.text(x,y,"a",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label11, contour='land')
    plt.close('all')
    a = label11.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1a_.tiff")
    system("convert -compress lzw /home/mag/Figure1a_.tiff /home/mag/Figure1a_.tiff")

    # Figure 1 b - HH
    plotRS2(SigmaHHwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.05), label=label22)
    plt.text(x,y,"b",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label22, contour='land')
    plt.close('all')
    a = label22.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1b_.tiff")
    system("convert -compress lzw /home/mag/Figure1b_.tiff /home/mag/Figure1b_.tiff")

    # Figure 1 c - polarization ratio (PR) (always<1)
    plotRS2(PR, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0.6,0.9), label=label33)
    plt.text(x,y,"c",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label3, contour='land')
    plt.close('all')
    a = label33.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1c_.tiff")
    system("convert -compress lzw /home/mag/Figure1c_.tiff /home/mag/Figure1c_.tiff")

    # Figure 1 d - polarization difference (PD) (always>0)
    plotRS2(delta, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.02), label=label4)
    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label4, contour='land')
    plt.close('all')
    a = label4.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1d_.tiff")
    system("convert -compress lzw /home/mag/Figure1d_.tiff /home/mag/Figure1d_.tiff")


    # Figure 4 - wave breaking contribution
    plotRS2(SigmaWb, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.03), label=label5)
    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label5, contour='land')
    plt.close('all')
    a = label5.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure4.tiff")
    system("convert -compress lzw /home/mag/Figure4.tiff /home/mag/Figure4.tiff")


    # Figure 3
    # Plot cropped Current
    ptsCropCurrent = array([[ 970, 3061], [2756, 5401]])
    CurrentVV = imcrop(ptsCropCurrent, SigmaVVwnr)
    CurrentPD = imcrop(ptsCropCurrent, delta)
    CurrentPR = imcrop(ptsCropCurrent, PR)
    CurrentWb = imcrop(ptsCropCurrent, SigmaWb)

    # Transect Current Front
#    pts = array([[1400, 4300], [2100, 3600]])
#    PDtrans = transect.transect(delta, pts, 30)[1]
#    PRtrans = transect.transect(PR, pts, 30)[1]
#    VVtrans = transect.transect(SigmaVVwnr, pts, 30)[1]
#    SigmaWbtrans = transect.transect(SigmaWb, pts, 30)[1]

#    Пока нет возможности сделать преобразование коорлинат, чтобы при помощи
#    imcrop находить координаты сечения исходного изображения в вырезанном.
#    Поэтому пока делаем сечение в вырезанной области, а в функцию plotTrnsImage
#    передаём исходные изображения и координаты для вырезания.
    pts = array([[ 650, 1700], [1230,  1000]])
    PDtrans = transect.transect(CurrentPD, pts, 30)[1]
    PRtrans = transect.transect(CurrentPR, pts, 30)[1]
    VVtrans = transect.transect(CurrentVV, pts, 30)[1]
    SigmaWbtrans = transect.transect(CurrentWb, pts, 30)[1]

    # setup nsper basemap
    # Lat/Lon coords of image corners
    lat_new, lon_new = intCrpLL(lat, lon, pixel, line, scale=1, ptsCrop=ptsCropCurrent)
    ll_lat = lat_new.min()
    ur_lat = lat_new.max()
    ll_lon = lon_new.min()
    ur_lon = lon_new.max()
    cent_lat = lat_new.mean()
    cent_lon = lon_new.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='c', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

    # Figure 3 a - VVtrans Image
    transect.plotTrnsImage(VVtrans, pts, lat, lon, SigmaVVwnr, pixel, line, \
                           pn='/home/mag/', \
                           label=label11, \
                           clm=(0.01,0.05), ptsCrop=ptsCropCurrent, m=m, scale=1, fign='a')
    plt.close('all')
    # Figure 3 b - VVtrans
    transect.plotTrns(VVtrans, pts, lat_new, lon_new, CurrentVV, \
                      pn='/home/mag/', \
                      label=label11, fign='b')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3a.tiff")
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-trns.tiff /home/mag/Figure3b.tiff")

    # Figure 3 c - PRtrans Image
    transect.plotTrnsImage(PRtrans, pts, lat, lon, PR, pixel, line, \
                           pn='/home/mag/', \
                           label=label33, \
                           clm=(0.65,0.9), ptsCrop=ptsCropCurrent, m=m, scale=1, fign='c')
    plt.close('all')
    # Figure 3 d - PRtrans
    transect.plotTrns(PRtrans, pts, lat_new, lon_new, CurrentPR, \
                      pn='/home/mag/', \
                      label=label33, fign='d')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3c.tiff")
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-trns.tiff /home/mag/Figure3d.tiff")

    # Figure 3 e - PDtrans Image
    transect.plotTrnsImage(PDtrans, pts, lat, lon, delta, pixel, line, \
                           pn='/home/mag/', \
                           label=label4, \
                           clm=(0.,0.02), ptsCrop=ptsCropCurrent, m=m, scale=1, fign='e')
    plt.close('all')
    # Figure 3 f - PRtrans
    transect.plotTrns(PDtrans, pts, lat_new, lon_new, CurrentPD, \
                      pn='/home/mag/', \
                      label=label4, fign='f')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3e.tiff")
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-trns.tiff /home/mag/Figure3f.tiff")

    # Figure 3 g - PDtrans Image
    transect.plotTrnsImage(SigmaWbtrans, pts, lat, lon, SigmaWb, pixel, line, \
                           pn='/home/mag/', \
                           label=label5, \
                           clm=(0.,0.03), ptsCrop=ptsCropCurrent, m=m, scale=1, fign='g')
    plt.close('all')
    # Figure 3 h - PRtrans
    transect.plotTrns(SigmaWbtrans, pts, lat_new, lon_new, CurrentWb, \
                      pn='/home/mag/', \
                      label=label5, fign='h')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-with-trns.tiff /home/mag/Figure3g.tiff")
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-trns.tiff /home/mag/Figure3h.tiff")



    # Figure 5
    # Plot cropped Northern Oil Spill
    lat_new, lon_new = intCrpLL(lat, lon, pixel, line, scale=1, ptsCrop=ptsCropNorth)
    ll_lat = lat_new.min()
    ur_lat = lat_new.max()
    ll_lon = lon_new.min()
    ur_lon = lon_new.max()
    cent_lat = lat_new.mean()
    cent_lon = lon_new.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='c', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

    # Transect North Oil Slick
    pts = array([[613, 851], [833, 1033]])

    # [1] returns only Mean Transect
    PDtrans = transect.transect(oilCropNorthDelta, pts, 30)[1]
    PRtrans = transect.transect(oilCropNorthPR, pts, 30)[1]
    VVtrans = transect.transect(oilCropNorthVV, pts, 30)[1]
    SigmaWbtrans = transect.transect(oilCropNorthSigmaWb, pts, 30)[1]

    # Figure 5 a - VVtrans Image
    transect.plotTrnsImage(VVtrans, pts, lat, lon, SigmaVVwnr, pixel, line, \
                           pn='/home/mag/', \
                           label=label11, \
                           clm=(0.01,0.05), ptsCrop=ptsCropNorth, m=m, scale=1, fign='a')
    plt.close('all')
    # Figure 5 b - VVtrans
    transect.plotTrns(VVtrans, pts, lat_new, lon_new, oilCropNorthVV, \
                      pn='/home/mag/', \
                      label=label11, fign='b')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5a.tiff")
    system("convert -compress lzw /home/mag/" + label11.split(' ')[0] + "-trns.tiff /home/mag/Figure5b.tiff")

    # Figure 5 c - PRtrans Image
    transect.plotTrnsImage(PRtrans, pts, lat, lon, PR, pixel, line, \
                           pn='/home/mag/', \
                           label=label33, \
                           clm=(0.65,0.9), ptsCrop=ptsCropNorth, m=m, scale=1, fign='c')
    plt.close('all')
    # Figure 5 d - PRtrans
    transect.plotTrns(PRtrans, pts, lat_new, lon_new, oilCropNorthPR, \
                      pn='/home/mag/', \
                      label=label33, fign='d')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5c.tiff")
    system("convert -compress lzw /home/mag/" + label33.split(' ')[0] + "-trns.tiff /home/mag/Figure5d.tiff")

    # Figure 5 e - PDtrans Image
    transect.plotTrnsImage(PDtrans, pts, lat, lon, delta, pixel, line, \
                           pn='/home/mag/', \
                           label=label4, \
                           clm=(0.,0.02), ptsCrop=ptsCropNorth, m=m, scale=1, fign='e')
    plt.close('all')
    # Figure 5 f - PRtrans
    transect.plotTrns(PDtrans, pts, lat_new, lon_new, oilCropNorthDelta, \
                      pn='/home/mag/', \
                      label=label4, fign='f')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5e.tiff")
    system("convert -compress lzw /home/mag/" + label4.split(' ')[0] + "-trns.tiff /home/mag/Figure5f.tiff")

    # Figure 5 g - PDtrans Image
    transect.plotTrnsImage(SigmaWbtrans, pts, lat, lon, SigmaWb, pixel, line, \
                           pn='/home/mag/', \
                           label=label5, \
                           clm=(0.,0.03), ptsCrop=ptsCropNorth, m=m, scale=1, fign='g')
    plt.close('all')
    # Figure 5 h - PRtrans
    transect.plotTrns(SigmaWbtrans, pts, lat_new, lon_new, oilCropNorthSigmaWb, \
                      pn='/home/mag/', \
                      label=label5, fign='h')
    plt.close('all')
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-with-trns.tiff /home/mag/Figure5g.tiff")
    system("convert -compress lzw /home/mag/" + label5.split(' ')[0] + "-trns.tiff /home/mag/Figure5h.tiff")

    # Clean up
    system("rm " + "/home/mag/*trns.tiff")
コード例 #25
0
def ctmf_med(image, radius):
    return median_filter(image=image, radius=radius)
コード例 #26
0
ファイル: DuPolfiguresGRL_draft.py プロジェクト: whigg/PySOL
def main( argv=None ):

    # default values
    pn = '/media/data/data/OTHER/RS2 Agulhas and Lion/RS2_FQA_1xQGSS20101218_173930_00000005/'
    xOff=0
    yOff=0
    xS=None
    yS=None
    xBufScale=None
    yBufScale=None
    s = 'abs'

    if argv is None:
        argv = sys.argv

    if argv is None:
        print ( "Please specify the path to the RS2 folder! \n" + \
                "See USAGE for more details \n")
        return Usage()

    # Parse arguments
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["pn=","xoff="])
    except getopt.GetoptError:
        print 'readRS2.py -pn <inputfile> ...'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'readRS2.py -pn <inputfile> ...'
            sys.exit()
        elif opt in ("-pn", "--pn"):
            pn = arg
        elif opt in ("-xoff", "--xoff"):
            xOff = arg
        elif opt in ("-yoff", "--yoff"):
            yOff = arg
        elif opt in ("-xS", "--xS"):
            xS = arg
        elif opt in ("-yS", "--yS"):
            yS = arg
        elif opt in ("-xScale", "--xScale"):
            xBufScale = arg
        elif opt in ("-yScale", "--yScale"):
            yBufScale = arg

    print "Path to the RS2 file:\n", pn

    if core_ct < 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calib = calibRS2(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, 'sigma0')
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calib.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calib.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calib.speckle_filter('wiener', 7)
        print 'Serial: time elapsed:', time() - currtime
    elif core_ct >= 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calibPar = calibRS2par(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, s)
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calibPar.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calibPar.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calibPar.speckle_filter('wiener', 7)
        print 'Parallel: time elapsed: %f' % ( time() - currtime )
        # export to geotiff
#        calibPar.save_tiff()

    print "Some Sigma calculations..."

    SigmaHHwnr = calibPar.SigmaHHwnr
    SigmaVVwnr = calibPar.SigmaVVwnr
#    SigmaHVwnr = calibPar.SigmaHVwnr

    # Free up some memory
    del calibPar.SigmaHHwnr, calibPar.SigmaVVwnr, calibPar.SigmaHVwnr

#    # Calculate some wind
#    # testing that with sar=-0.387 wind speed is 10m/s
#    w = rcs2wind(sar=-0.387*ones((1,1)), cmdv=4, windir=0, theta=20*ones((1,1)))
#    print "Testing CMOD4 passed, Wind =", w
#
#    sar=10*log10(SigmaVVwnr[::10,::10])
##    sar=10*log10(SigmaVVwnr)
#    w = rcs2wind(sar, cmdv=4, windir=130, theta=33*ones(sar.shape))
#    print "Mean CMOD4 Wind =", w.mean()

    # calculate the conjugate
    SigmaVVConjHH = calibPar.S_VV*conj(calibPar.S_HH)
    SigmaVVConjHHWnr = wiener(SigmaVVConjHH, mysize=(7,7), noise=None)
    # all sigmas in linear units
    SigmaVVConjHHdelta = SigmaVVConjHHWnr/(SigmaVVwnr - SigmaHHwnr)

#    # Check that imagenary part is much less then the real one
#    SigmaVVConjHHr = real(SigmaVVConjHH)
#    SigmaVVConjHHi = imag(SigmaVVConjHH)
#    SigmaVVConjHHr.mean()
#    SigmaVVConjHHi.mean()

    # Free up some memory
    del SigmaVVConjHH, calibPar.S_HH, calibPar.S_VV

    # 2. Find Poolarization ratio PR in dB and delta - linear
    # delta - is a Bragg component, which describes wind field impact
    # PR = 10*log10(SigmaHHwnr) - 10*log10(SigmaVVwnr)
#    # PR must not be > 0, be careful with masking
    #P[P>0] = 0
    PR = SigmaHHwnr/SigmaVVwnr
    delta = SigmaVVwnr - SigmaHHwnr



#    # Masking Land from HV polarization
#    maskedLand = SigmaHVwnr>0.003

    # 3. Linear fit of Sigma and delta: Sigma = A*delta
#    A = sum(SigmaVVwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
#    B = sum(SigmaHHwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
    # imposing from theory
    A = linspace(2.3,1.8,IncidenceAngle.size) # dependence on inc angle
    A = tile(A, (line[-1,0]+1, 1))

    # 4. Calculate SigmaVVwb = SigmaVVwb === SigmaHHwb
    # substracting wind field variability contribution, the rest is impact of
    # current and film on the image
    SigmaWb = SigmaVVwnr - ( A*delta )

    # Checking that SigmaWb from VV and HH are the same
    # SigmaVVwb = SigmaVVwnr - ( A*delta )
    # SigmaHHwb = SigmaHHwnr - ( B*delta )
    # SigmaWb = SigmaVVwb
    # mean(SigmaHHwb(:)./SigmaVVwb(:))
    # clear SigmaVVwb SigmaHHwb

    # Cropping the oil slicks

#    проверить почему переворот изображения!!!
#    print ( "Cropping...")
#    plt.figure()
#    plt.imshow(delta)
#    plt.clim(-0.01,0.03)
#    plt.gray()
#    plt.show()
#    pts = imzoom()

    ptsCropSouth = array([[ 3200, 4550],
                          [ 3800, 5100]])
    oilCropSouth = imcrop(ptsCropSouth, delta)
    ptsCropNorth = array([[ 3400, 0],
                          [ 4900,  1650]])
    oilCropNorth = imcrop(ptsCropNorth, delta)

    # reduce the speckle noise
    oilN = wiener(oilCropNorth, mysize=(3,3), noise=None)
    oilS = wiener(oilCropSouth, mysize=(3,3), noise=None)

    # use median filter to smooth
    oilN = median_filter(oilN, radius=37)
    oilS = median_filter(oilS, radius=37)

    # find the global threshold
    global_threshN = threshold_otsu(oilN)
    global_threshS = threshold_otsu(oilS)

    # create a binary mask
    markersN = ones(oilN.shape, dtype=uint)
    markersS = ones(oilS.shape, dtype=uint)
    markersN[oilN < global_threshN*0.84] = 0
    markersS[oilS < global_threshS*0.84] = 0

    # Find the relation of PR in/out-side the Slicks
    oilCropNorthPR = imcrop(ptsCropNorth, PR)
    oilCropPN = oilCropNorthPR[markersN==0].mean()/oilCropNorthPR[markersS==1].mean()

    oilCropSouthP = imcrop(ptsCropSouth, PR)
    oilCropPS = oilCropSouthP[markersS==0].mean()/oilCropSouthP[markersS==1].mean()

    # Checking that calculations are OK
    oilCropNorthKVV = imcrop(ptsCropNorth, SigmaVVwnr)
    KVV = oilCropNorthKVV[markersN==0].mean()/oilCropNorthKVV[markersN==1].mean()
    oilCropNorthKHH = imcrop(ptsCropNorth, SigmaHHwnr)
    KHH = oilCropNorthKHH[markersN==0].mean()/oilCropNorthKHH[markersN==1].mean()
    PSlick = KHH/KVV*oilCropNorthKHH[markersN==1].mean()/oilCropNorthKVV[markersN==1].mean()

    print "Polarization ratio Out/In-side Slick = \
        \n %0.2f for Northern \n %0.2f for Southern" \
        %(1/oilCropPN, 1/oilCropPS)

    oilCropNorthVV = imcrop(ptsCropNorth, SigmaVVwnr)
    oilCropNorthDelta = imcrop(ptsCropNorth, delta)
    oilCropNorthSigmaWb = imcrop(ptsCropNorth, SigmaWb)





    # Interpolating lat/lon to image size for future pcolormesh
    from numpy import linspace, arange, round, floor, ceil
    from scipy.interpolate import interp2d
    def interpLL(l, pixel, line, gx, gy):
        """
        Interpolating lat/lon to image size for future pcolormesh
        """
        fl = interp2d(pixel[0,:], line[:,0], l, kind='linear')
        l_new = fl(gx, gy)
        return l_new

    ptsCrop = ptsCropNorth
    RasterXSize = round((-ptsCrop[0,0]+ptsCrop[-1,0]))
    RasterYSize = round((-ptsCrop[0,-1]+ptsCrop[-1,-1]))
    gx = linspace(ptsCrop[0,0], ptsCrop[-1,0], RasterXSize+1)
    gy = linspace(ptsCrop[0,-1], ptsCrop[-1,-1], RasterYSize+1)
    
    RasterXSize = round(pixel[0,-1])
    RasterYSize = round(line[-1,0])
    gx = linspace(0, pixel[0,-1], RasterXSize+1)
    gy = linspace(0, line[-1,0], RasterYSize+1)    
    
    lat_new = interpLL(lat, pixel, line, gx, gy)
    lon_new = interpLL(lon, pixel, line, gx, gy)

    # save to MAT file
    from scipy.io import savemat
    print "Exporting"
    pn = '/home/mag/Documents/MATLAB/Leon_Agulhas_RS2/'
    expFn = 'OilSlickTrns/OilSlickTrns.mat'
    if not path.isfile(pn + expFn):
        print "Exporting to:\n" , pn + expFn
        savemat(pn + expFn, mdict={ \
                'VV':oilCropNorthVV, \
                'PD':oilCropNorthDelta, \
                'SigmaWb':oilCropNorthSigmaWb, \
                'PR':oilCropNorthPR, \
                'lat':lat_new, 'lon':lon_new, \
                }, do_compression=False)

    expFn = 'CurrentFrontTrns/CurrentFrontTrns.mat'
    if not path.isfile(pn + expFn):
        print "Exporting to:\n" , pn + expFn
        savemat(pn + expFn, mdict={ \
                'PD':delta, \
                'PR':PR, \
                'VV':SigmaVVwnr, \
                'SigmaWb':SigmaWb, \
                'lat':lat_new, 'lon':lon_new, \
                }, do_compression=False)

    import h5py
    pn = '/home/mag/Documents/MATLAB/Leon_Agulhas_RS2/'
    expFn = 'CurrentFrontTrns/CurrentFrontTrns.mat'
    expFn = 'OilSlickTrns/OilSlickTrns.mat'
    f = h5py.File(pn + expFn)
    SigmaWb = f["SigmaWb"]
    SigmaWb = flipud(rot90(array(SigmaWb)))
    lat = f["lat"]
    lat = flipud(rot90(array(lat)))
    lon = f["lon"]
    lon = flipud(rot90(array(lon)))
    y = f["tWb"]['transx']
    y = array(y)
    x = f["tWb"]['transy']
    x = array(x)
    pts = zeros((2,2))
    pts[:,0] = x
    pts[:,1] = y
#    transec_init = f["tWb"]['transec_init']
#    transec_init = array(transec_init)

    import distancelib
    reload(distancelib)
    # Get pixel resolution in Col/Row direction
    PxResCol, PxResRow = distancelib.getPixelResolution(lat, lon, SigmaWb)
    # Get the length of the transect. Input coords in (row,col)
    trnsLength = distancelib.getDistancePx([pts[0,1], pts[0,0]], [pts[1,1], pts[1,0]], lat, lon, SigmaWb)

    import transect
    reload(transect)
    transect.plotTrns(SigmaWbtrans, pts, lat, lon, SigmaWb, pn)




    # Making transect
    plt.figure()
    plt.imshow(oilCropNorthDelta)
    plt.gray()
    plt.clim(0, 0.02)
    plt.colorbar()
    pts = transect.imagePts()
    plt.savefig('/home/mag/PDtrns.png', facecolor='w', edgecolor='w', \
                 dpi=100, bbox_inches="tight", pad_inches=1.75)

    # Transect North Oil Slick
    pts = array([[610, 871], [822, 1007]])

    # [1] returns only Mean Transect
    PDtrans = transect.transect(oilCropNorthDelta, pts, 30)[1]
    PRtrans = transect.transect(oilCropNorthPR, pts, 30)[1]
    VVtrans = transect.transect(oilCropNorthVV, pts, 30)[1]
    SigmaWbtrans = transect.transect(oilCropNorthSigmaWb, pts, 30)[1]

#    PDtrans = transect.transect(oilCropNorthDelta, pts, 100)[0]






    plt.figure()
    plt.imshow(CurrentWb)
    plt.gray()
    plt.clim(0, 0.03)
    plt.colorbar()
    pts = transect.imagePts()
    plt.savefig('/home/mag/PDtrns.png', facecolor='w', edgecolor='w', \
                 dpi=100, bbox_inches="tight", pad_inches=1.75)

    # Transect Current Front
    pts = array([[1207., 4318.], [2473., 3763.]])
    
    PDtrans = transect.transect(delta, pts, 30)[1]
    PRtrans = transect.transect(PR, pts, 30)[1]
    VVtrans = transect.transect(SigmaVVwnr, pts, 30)[1]
    
    SigmaWbtrans = transect.transect(SigmaWb, pts, 30, method='cubic')[1]



    # use median filter to smooth
    from scipy.ndimage import median_filter as mflt
    PRtransSmthd = mflt(PRtrans, size=21, mode='nearest')
    PDtransSmthd = mflt(PDtrans, size=21, mode='nearest')
    VVtransSmthd = mflt(VVtrans, size=21, mode='nearest')
    SigmaWbtransSmthd = mflt(SigmaWbtrans, size=21, mode='nearest')

    plt.figure()
#    plt.imshow(SigmaWb)
    plt.imshow(SigmaWb)
    plt.gray()
    plt.clim(0, 0.02)
    plt.colorbar()
    ax = plt.gca().get_xbound()
    ay = plt.gca().get_ybound()
    x = pts[:, 0]
    y = pts[:, 1]
    plt.plot(x, y, '-o')
    plt.text(x[0],y[0],"A",bbox=dict(facecolor='w', alpha=0.7),stretch='expanded',fontsize=21)
    plt.text(x[1],y[1],"B",bbox=dict(facecolor='w', alpha=0.7),stretch='expanded',fontsize=21)
    plt.gca().set_xbound(ax)
    plt.gca().set_ybound(ay)
    plt.draw()
#    window = gtk.Window()
#    screen = window.get_screen()
#    width = screen.get_width()
#    height = screen.get_height()
#    mng = plt.get_current_fig_manager()
#    mng.resize(width, height)
    plt.savefig('/home/mag/PDtrns.png', facecolor='w', edgecolor='w', \
                 dpi=100, bbox_inches="tight", pad_inches=1.75)

    plt.figure()
    plt.plot(PDtransSmthd)
    plt.grid()
#    window = gtk.Window()
#    screen = window.get_screen()
#    width = screen.get_width()
#    height = screen.get_height()
#    mng = plt.get_current_fig_manager()
#    mng.resize(width, height)
    plt.savefig('/home/mag/PDtrnsLine.png', facecolor='w', edgecolor='w', \
                 dpi=100, bbox_inches="tight", pad_inches=1.75)

    plt.figure()
    plt.plot(PRtransSmthd)
    plt.grid()
#    window = gtk.Window()
#    screen = window.get_screen()
#    width = screen.get_width()
#    height = screen.get_height()
#    mng = plt.get_current_fig_manager()
#    mng.resize(width, height)
    plt.savefig('/home/mag/PRtransLine.png', facecolor='w', edgecolor='w', \
                 dpi=100, bbox_inches="tight", pad_inches=1.75)

    plt.figure()
    plt.plot(VVtransSmthd)
    plt.grid()
#    window = gtk.Window()
#    screen = window.get_screen()
#    width = screen.get_width()
#    height = screen.get_height()
#    mng = plt.get_current_fig_manager()
#    mng.resize(width, height)
    plt.savefig('/home/mag/VVtransLine.png', facecolor='w', edgecolor='w', \
                 dpi=100, bbox_inches="tight", pad_inches=1.75)

    plt.figure()
    plt.plot(SigmaWbtransSmthd)
    plt.grid()
#    window = gtk.Window()
#    screen = window.get_screen()
#    width = screen.get_width()
#    height = screen.get_height()
#    mng = plt.get_current_fig_manager()
#    mng.resize(width, height)
    plt.savefig('/home/mag/SigmaWbtransLine.png', facecolor='w', edgecolor='w', \
                 dpi=100, bbox_inches="tight", pad_inches=1.75)

    plt.close('all')


    print ( "Plotting on a map... \nUsing default NSPER Basemap \n")

    # setup nsper basemap
    # Lat/Lon coords of image corners
    ll_lat = lat.min()
    ur_lat = lat.max()
    ll_lon = lon.min()
    ur_lon = lon.max()
    cent_lat = lat.mean()
    cent_lon = lon.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='f', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

#    m = Basemap(llcrnrlat=30, urcrnrlat=50,\
#                llcrnrlon=1, urcrnrlon=20, \
#                resolution='l', projection='nsper', \
#                satellite_height=798000, \
#                lat_0=cent_lat,lon_0=cent_lon)

    print ( "Plotting figures... \n")

    scale = 8 # setting scale factor to resize in 1/scale times
    label1 = 'Sigma VV [dB]'
    label2 = 'Sigma HH [dB]'
    label11 = 'Sigma VV [linear units]'
    label22 = 'Sigma HH [linear units]'
    label3 = 'PR [dB]'
    label33 = 'PR [linear units]'
    label4 = 'PD [linear units]'
    label5 = 'Wb contribution [linear units]'
    label6 = 'SigmaVVConjHH [linear units]'
    label7 = 'SigmaVVConjHHdelta [linear units]'

#    label8 = 'Wind CMOD4 [m/s]'

    import plotRS2
    reload(plotRS2)
    from plotRS2 import plotRS2

#    import mpl_util
#    reload(mpl_util)
#
#    import gmtColormap
#    reload(gmtColormap)
#
#    import createMapsEtopo1
#    reload(createMapsEtopo1)
#    from createMapsEtopo1 import makeMap
#
#    import g1sst
#    reload(g1sst)
#    from g1sst import g1sst

#    plotRS2(10*log10(SigmaVVwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label1)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label1, contour='land')
#    plt.close('all')
#
#    plotRS2(10*log10(SigmaHHwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label2)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label2, contour='land')
#    plt.close('all')
#    plotRS2(PR, lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-2.7,0), label=label3)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label3, contour='land')
#    plt.close('all')

    # Coords to plot Figure number
    x, y = m(3.15, 42.15)

    # Figure 1 a - VV
    plotRS2(SigmaVVwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.05), label=label11)
    plt.text(x,y,"a",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label11, contour='land')
    plt.close('all')
    a = label11.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1a.tiff")
    system("convert -compress lzw /home/mag/Figure1a.tiff /home/mag/Figure1a.tiff")

    # Figure 1 b - HH
    plotRS2(SigmaHHwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.05), label=label22)
    plt.text(x,y,"b",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label22, contour='land')
    plt.close('all')
    a = label22.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1b.tiff")
    system("convert -compress lzw /home/mag/Figure1b.tiff /home/mag/Figure1b.tiff")

    # Figure 1 c - polarization ratio (PR) (always<1)
    plotRS2(PR, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0.4,1), label=label33)
    plt.text(x,y,"c",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label3, contour='land')
    plt.close('all')
    a = label33.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1c.tiff")
    system("convert -compress lzw /home/mag/Figure1c.tiff /home/mag/Figure1c.tiff")

    # Figure 1 d - polarization difference (PD) (always>0)
    plotRS2(delta, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.02), label=label4)
    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label4, contour='land')
    plt.close('all')
    a = label4.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1d.tiff")
    system("convert -compress lzw /home/mag/Figure1d.tiff /home/mag/Figure1d.tiff")


    # Figure 4 - wave breaking contribution
    plotRS2(SigmaWb, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.03), label=label5)
    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label5, contour='land')
    plt.close('all')
    a = label5.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure4.tiff")
    system("convert -compress lzw /home/mag/Figure4.tiff /home/mag/Figure4.tiff")

    import transect
    reload(transect)
    transect.plotTrns(SigmaWbtrans, pts, lat, lon, SigmaWb, pn)


    # Figure 3
    # Plot cropped Oil Spills
    # Northern
    # setup nsper basemap
    # Lat/Lon coords of image corners
    lat_new, lon_new = intCrpLL(lat, lon, pixel, line, scale=1, ptsCrop=ptsCropNorth)
    ll_lat = lat_new.min()
    ur_lat = lat_new.max()
    ll_lon = lon_new.min()
    ur_lon = lon_new.max()
    cent_lat = lat_new.mean()
    cent_lon = lon_new.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='c', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)
    # Coords to plot Figure number
    xSl, ySl = m(3.473, 42.173)
    # Figure 3 a - VV
    plotRS2(SigmaVVwnr, lat, lon, pixel, line, \
            scale=1, m=m, clm=(0,0.05), label=label11, ptsCrop=ptsCropNorth)
    plt.text(xSl,ySl,"a",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    plt.savefig('/home/mag/Figure3a.tiff', facecolor='w', edgecolor='w', \
                 dpi=300, bbox_inches="tight", pad_inches=1.75)
    plt.close('all')
    # Figure 3 b - PR
    plotRS2(PR, lat, lon, pixel, line, \
            scale=1, m=m, clm=(0.5,1), label=label33, ptsCrop=ptsCropNorth)
    plt.text(xSl,ySl,"b",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
    plt.savefig('/home/mag/Figure3b.tiff', facecolor='w', edgecolor='w', \
                 dpi=300, bbox_inches="tight", pad_inches=1.75)
    plt.close('all')
#    # Figure 3 c - PD  (always>0)
#    plotRS2(delta, lat, lon, pixel, line, \
#            scale=1, m=m, clm=(0,0.03), label=label4, ptsCrop=ptsCropNorth)
#    plt.text(xSl,ySl,"c",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
#    plt.savefig('/home/mag/Figure3c.tiff', facecolor='w', edgecolor='w', \
#                 dpi=300, bbox_inches="tight", pad_inches=1.75)
#    plt.close('all')
    system("convert -compress lzw /home/mag/Figure3a.tiff /home/mag/Figure3a.tiff")
    system("convert -compress lzw /home/mag/Figure3b.tiff /home/mag/Figure3b.tiff")
#    system("convert -compress lzw /home/mag/Figure3c.tiff /home/mag/Figure3c.tiff")
#    # Southern
#        # setup nsper basemap
#    # Lat/Lon coords of image corners
#    lat_new, lon_new = intCrpLL(lat, lon, pixel, line, scale=1, ptsCrop=ptsCropSouth)
#    ll_lat = lat_new.min()
#    ur_lat = lat_new.max()
#    ll_lon = lon_new.min()
#    ur_lon = lon_new.max()
#    cent_lat = lat_new.mean()
#    cent_lon = lon_new.mean()
#    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
#                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
#                resolution='c', projection='nsper', \
#                satellite_height=798000, \
#                lat_0=cent_lat,lon_0=cent_lon)
#    # Coords to plot Figure number
#    xSl, ySl = m(3.491, 41.973)
#    # Figure 3 d - VV
#    plotRS2(SigmaVVwnr, lat, lon, pixel, line, \
#            scale=1, m=m, clm=(0,0.05), label=label11, ptsCrop=ptsCropSouth)
#    plt.text(xSl,ySl,"d",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
#    plt.savefig('/home/mag/Figure3d.tiff', facecolor='w', edgecolor='w', \
#                 dpi=300, bbox_inches="tight", pad_inches=1.75)
#    plt.close('all')
#    # Figure 3 e - PR (always<1)
#    plotRS2(PR, lat, lon, pixel, line, \
#            scale=1, m=m, clm=(0.4,1), label=label33, ptsCrop=ptsCropSouth)
#    plt.text(xSl,ySl,"e",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
#    plt.savefig('/home/mag/Figure3e.tiff', facecolor='w', edgecolor='w', \
#                 dpi=300, bbox_inches="tight", pad_inches=1.75)
#    plt.close('all')
#    # Figure 3 f - PD  (always>0)
#    plotRS2(delta, lat, lon, pixel, line, \
#            scale=1, m=m, clm=(0,0.03), label=label4, ptsCrop=ptsCropSouth)
#    plt.text(xSl,ySl,"f",bbox=dict(facecolor='w', alpha=0.5),stretch='expanded',fontsize=27)
#    plt.savefig('/home/mag/Figure3f.tiff', facecolor='w', edgecolor='w', \
#                 dpi=300, bbox_inches="tight", pad_inches=1.75)
#    plt.close('all')
#    system("convert -compress lzw /home/mag/Figure3d.tiff /home/mag/Figure3d.tiff")
#    system("convert -compress lzw /home/mag/Figure3e.tiff /home/mag/Figure3e.tiff")
#    system("convert -compress lzw /home/mag/Figure3f.tiff /home/mag/Figure3f.tiff")
    import transect
    reload(transect)
    transect.plotTrns(PRtrans, pts, lat, lon, PR, pixel, line, pn='/home/mag/', \
                      label='PR [linear units]', clm=(0.5,1), \
                      ptsCrop=ptsCropNorth, m=m, scale=1)
コード例 #27
0
def test_default_values():
    img = (np.random.random((20, 20)) * 255).astype(np.uint8)
    mask = np.ones((20, 20), dtype=np.uint8)
    result1 = median_filter(img, radius=2, mask=mask, percent=50)
    result2 = median_filter(img)
    np.testing.assert_array_equal(result1, result2)
コード例 #28
0
def test_00_00_zeros():
    '''The median filter on an array of all zeros should be zero'''
    result = median_filter(np.zeros((10, 10)), 3, np.ones((10, 10), bool))
    assert np.all(result == 0)
コード例 #29
0
def test_wrong_shape():
    img = np.empty((10, 10, 3))
    median_filter(img)
コード例 #30
0
"""
This example compares several denoising filters available in scikit-image:
a Gaussian filter, a median filter, and total variation denoising.
"""

import matplotlib.pyplot as plt
from skimage import data
from skimage import filter
from scipy import ndimage

coins = data.coins()
gaussian_filter_coins = ndimage.gaussian_filter(coins, sigma=2)
med_filter_coins = filter.median_filter(coins)
tv_filter_coins = filter.tv_denoise(coins, weight=0.1)

plt.figure(figsize=(16, 4))
plt.subplot(141)
plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest')
plt.axis('off')
plt.title('Image')
plt.subplot(142)
plt.imshow(gaussian_filter_coins[10:80, 300:370],
           cmap='gray',
           interpolation='nearest')
plt.axis('off')
plt.title('Gaussian filter')
plt.subplot(143)
plt.imshow(med_filter_coins[10:80, 300:370],
           cmap='gray',
           interpolation='nearest')
plt.axis('off')
コード例 #31
0
def test_00_00_zeros():
    '''The median filter on an array of all zeros should be zero'''
    result = median_filter(np.zeros((10, 10)), 3, np.ones((10, 10), bool))
    assert np.all(result == 0)
コード例 #32
0
def ctmf_med(image, radius):
    return median_filter(image=image, radius=radius)
コード例 #33
0
ファイル: DuPolfiguresAPSAR.py プロジェクト: lelou6666/PySOL
def main( argv=None ):

    # default values
    #~ pn = '/media/data/data/OTHER/RS2 Agulhas and Lion/RS2_FQA_1xQGSS20101218_173930_00000005/'
    pn = '/media/data/data/OTHER/RS2 Agulhas and Lion/RS2_SQA_1xQGSS20091224_164846_00000004/'
    #~ pn = '/media/data/data/OTHER/WhiteSea2012/RS-2/RS2_FQA_1xQGSS20120729_144551_00000005xQ12_16bxx_24139_FC556/'
    xOff=0
    yOff=0
    xS=None
    yS=None
    xBufScale=None
    yBufScale=None
    s = 'abs'

    if argv is None:
        argv = sys.argv

    if argv is None:
        print ( "Please specify the path to the RS2 folder! \n" + \
                "See USAGE for more details \n")
        return Usage()

    # Parse arguments
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["pn=","xoff="])
    except getopt.GetoptError:
        print 'readRS2.py -pn <inputfile> ...'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'readRS2.py -pn <inputfile> ...'
            sys.exit()
        elif opt in ("-pn", "--pn"):
            pn = arg
        elif opt in ("-xoff", "--xoff"):
            xOff = arg
        elif opt in ("-yoff", "--yoff"):
            yOff = arg
        elif opt in ("-xS", "--xS"):
            xS = arg
        elif opt in ("-yS", "--yS"):
            yS = arg
        elif opt in ("-xScale", "--xScale"):
            xBufScale = arg
        elif opt in ("-yScale", "--yScale"):
            yBufScale = arg

    print "Path to the RS2 file:\n", pn

    if core_ct < 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calib = calibRS2(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, 'sigma0')
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calib.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calib.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calib.speckle_filter('wiener', 7)
        print 'Serial: time elapsed:', time() - currtime
    elif core_ct >= 4:
        # calibrate the scene
        print "Calibrating"
        currtime = time()
        calibPar = calibRS2par(pn, xOff, yOff, xS, yS, xBufScale, yBufScale, s)
        # get the incidence angle
        print "Incidence Angle and Lats/Lons"
        IncidenceAngle = calibPar.incidence_angle()
        IncidenceAngle = rad2deg(IncidenceAngle)
        # get the lats/lons
        (lat, lon, line, pixel) = calibPar.xml2geo()
        print "Filtering"
        # 1. Remove speckle noise (using Lee-Wiener filter)
        calibPar.speckle_filter('wiener', 7)
        print 'Parallel: time elapsed: %f' % ( time() - currtime )
        # export to geotiff
#        calibPar.save_tiff()

    print "Some Sigma calculations..."

    SigmaHHwnr = calibPar.SigmaHHwnr
    SigmaVVwnr = calibPar.SigmaVVwnr
#    SigmaHVwnr = calibPar.SigmaHVwnr

    # Free up some memory
    del calibPar.SigmaHHwnr, calibPar.SigmaVVwnr, calibPar.SigmaHVwnr

#    # Calculate some wind
#    # testing that with sar=-0.387 wind speed is 10m/s
#    w = rcs2wind(sar=-0.387*ones((1,1)), cmdv=4, windir=0, theta=20*ones((1,1)))
#    print "Testing CMOD4 passed, Wind =", w
#
#    sar=10*log10(SigmaVVwnr[::10,::10])
##    sar=10*log10(SigmaVVwnr)
#    w = rcs2wind(sar, cmdv=4, windir=130, theta=33*ones(sar.shape))
#    print "Mean CMOD4 Wind =", w.mean()

    # calculate the conjugate
    SigmaVVConjHH = calibPar.S_VV*conj(calibPar.S_HH)
    SigmaVVConjHHWnr = wiener(SigmaVVConjHH, mysize=(7,7), noise=None)
    # all sigmas in linear units
    SigmaVVConjHHdelta = SigmaVVConjHHWnr/(SigmaVVwnr - SigmaHHwnr)

#    # Check that imagenary part is much less then the real one
#    SigmaVVConjHHr = real(SigmaVVConjHH)
#    SigmaVVConjHHi = imag(SigmaVVConjHH)
#    SigmaVVConjHHr.mean()
#    SigmaVVConjHHi.mean()

    # Free up some memory
    del SigmaVVConjHH, calibPar.S_HH, calibPar.S_VV

    # 2. Find Poolarization ratio PR in dB and delta - linear
    # delta - is a Bragg component, which describes wind field impact
    # PR = 10*log10(SigmaHHwnr) - 10*log10(SigmaVVwnr)
#    # PR must not be > 0, be careful with masking
    #P[P>0] = 0
    PR = SigmaHHwnr/SigmaVVwnr
    delta = SigmaVVwnr - SigmaHHwnr



#    # Masking Land from HV polarization
#    maskedLand = SigmaHVwnr>0.003

    # 3. Linear fit of Sigma and delta: Sigma = A*delta
#    A = sum(SigmaVVwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
#    B = sum(SigmaHHwnr[~maskedLand]*delta[~maskedLand])/sum(delta[~maskedLand]^2);
    # imposing from theory
    A = linspace(2.3,1.8,IncidenceAngle.size) # dependence on inc angle
    A = tile(A, (line[-1,0]+1, 1))

    # 4. Calculate SigmaVVwb = SigmaVVwb === SigmaHHwb
    # substracting wind field variability contribution, the rest is impact of
    # current and film on the image
    SigmaWb = SigmaVVwnr - ( A*delta )

    # Checking that SigmaWb from VV and HH are the same
    # SigmaVVwb = SigmaVVwnr - ( A*delta )
    # SigmaHHwb = SigmaHHwnr - ( B*delta )
    # SigmaWb = SigmaVVwb
    # mean(SigmaHHwb(:)./SigmaVVwb(:))
    # clear SigmaVVwb SigmaHHwb

    # Cropping the oil slicks

##    проверить почему переворот изображения!!!
#    from imcrop import imzoom
#    print ( "Cropping...")
#    plt.figure()
#    plt.imshow(SigmaWb)
#    plt.clim(0,0.03)
#    plt.gray()
#    plt.show()
#    pts = imzoom()

    ptsCropSouth = array([[ 3200, 4550],
                          [ 3800, 5100]])
    oilCropSouth = imcrop(ptsCropSouth, delta)
    ptsCropNorth = array([[ 3400, 0],
                          [ 4900,  1650]])
    oilCropNorth = imcrop(ptsCropNorth, delta)

    # reduce the speckle noise
    oilN = wiener(oilCropNorth, mysize=(3,3), noise=None)
    oilS = wiener(oilCropSouth, mysize=(3,3), noise=None)

    # use median filter to smooth
    oilN = median_filter(oilN, radius=37)
    oilS = median_filter(oilS, radius=37)

    # find the global threshold
    global_threshN = threshold_otsu(oilN)
    global_threshS = threshold_otsu(oilS)

    # create a binary mask
    markersN = ones(oilN.shape, dtype=uint)
    markersS = ones(oilS.shape, dtype=uint)
    markersN[oilN < global_threshN*0.84] = 0
    markersS[oilS < global_threshS*0.84] = 0

    # Find the relation of PR in/out-side the Slicks
    oilCropNorthPR = imcrop(ptsCropNorth, PR)
    oilCropPN = oilCropNorthPR[markersN==0].mean()/oilCropNorthPR[markersS==1].mean()

    oilCropSouthP = imcrop(ptsCropSouth, PR)
    oilCropPS = oilCropSouthP[markersS==0].mean()/oilCropSouthP[markersS==1].mean()

    # Checking that calculations are OK
    oilCropNorthKVV = imcrop(ptsCropNorth, SigmaVVwnr)
    KVV = oilCropNorthKVV[markersN==0].mean()/oilCropNorthKVV[markersN==1].mean()
    oilCropNorthKHH = imcrop(ptsCropNorth, SigmaHHwnr)
    KHH = oilCropNorthKHH[markersN==0].mean()/oilCropNorthKHH[markersN==1].mean()
    PSlick = KHH/KVV*oilCropNorthKHH[markersN==1].mean()/oilCropNorthKVV[markersN==1].mean()

    print "Polarization ratio Out/In-side Slick = \
        \n %0.2f for Northern \n %0.2f for Southern" \
        %(1/oilCropPN, 1/oilCropPS)

    oilCropNorthVV = imcrop(ptsCropNorth, SigmaVVwnr)
    oilCropNorthDelta = imcrop(ptsCropNorth, delta)
    oilCropNorthSigmaWb = imcrop(ptsCropNorth, SigmaWb)

    print ( "Plotting on a map... \nUsing default NSPER Basemap \n")

    # setup nsper basemap
    # Lat/Lon coords of image corners
    ll_lat = lat.min()
    ur_lat = lat.max()
    ll_lon = lon.min()
    ur_lon = lon.max()
    cent_lat = lat.mean()
    cent_lon = lon.mean()
    m = Basemap(llcrnrlat=ll_lat, urcrnrlat=ur_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, \
                resolution='f', projection='nsper', \
                satellite_height=798000, \
                lat_0=cent_lat,lon_0=cent_lon)

#    m = Basemap(llcrnrlat=30, urcrnrlat=50,\
#                llcrnrlon=1, urcrnrlon=20, \
#                resolution='l', projection='nsper', \
#                satellite_height=798000, \
#                lat_0=cent_lat,lon_0=cent_lon)

    print ( "Plotting figures... \n")

    scale = 8 # setting scale factor to resize in 1/scale times
    label1 = 'Sigma VV [dB]'
    label2 = 'Sigma HH [dB]'
    label11 = 'Sigma VV [linear units]'
    label22 = 'Sigma HH [linear units]'
    label3 = 'PR [dB]'
    label33 = 'PR [linear units]'
    label4 = 'PD [linear units]'
    label5 = 'Wb contribution [linear units]'
    label6 = 'SigmaVVConjHH [linear units]'
    label7 = 'SigmaVVConjHHdelta [linear units]'

#    label8 = 'Wind CMOD4 [m/s]'

#    import plotRS2
#    reload(plotRS2)
#    from plotRS2 import plotRS2

#    import mpl_util
#    reload(mpl_util)
#
#    import gmtColormap
#    reload(gmtColormap)
#
#    import createMapsEtopo1
#    reload(createMapsEtopo1)
#    from createMapsEtopo1 import makeMap
#
#    import g1sst
#    reload(g1sst)
#    from g1sst import g1sst

#    plotRS2(10*log10(SigmaVVwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label1)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label1, contour='land')
#    plt.close('all')
#
#    plotRS2(10*log10(SigmaHHwnr), lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-25,-5), label=label2)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label2, contour='land')
#    plt.close('all')
#    plotRS2(PR, lat, lon, pixel, line, \
#            scale=scale, m=m, clm=(-2.7,0), label=label3)
#    makeMap(ll_lon, ur_lon, \
#            ll_lat, ur_lat, m, name=label3, contour='land')
#    plt.close('all')

    # Coords to plot Figure number
    #~ x, y = m(3.15, 42.15) # for Lion
    x, y = m(27.97, -32.81)  # for Agulhas
    #~ x, y = m(27.97, -32.81)  # for WhiteSea Gorlo
    
    # Figure 1 a - VV
    plotRS2(SigmaVVwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.1), label=label11)
    plt.text(x,y,"a",bbox=dict(facecolor='w', alpha=1),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label11, contour='land')
    plt.close('all')
    a = label11.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1a_.tiff")
    system("convert -compress lzw /home/mag/Figure1a_.tiff /home/mag/Figure1a_.tiff")

    # Figure 1 b - HH
    plotRS2(SigmaHHwnr, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.1), label=label22)
    plt.text(x,y,"b",bbox=dict(facecolor='w', alpha=1),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label22, contour='land')
    plt.close('all')
    a = label22.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1b_.tiff")
    system("convert -compress lzw /home/mag/Figure1b_.tiff /home/mag/Figure1b_.tiff")

    # Figure 1 c - polarization ratio (PR) (always<1)
    plotRS2(PR, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0.65,0.95), label=label33)
    plt.text(x,y,"c",bbox=dict(facecolor='w', alpha=1),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label3, contour='land')
    plt.close('all')
    a = label33.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1c_.tiff")
    system("convert -compress lzw /home/mag/Figure1c_.tiff /home/mag/Figure1c_.tiff")

    # Figure 1 d - polarization difference (PD) (always>0)
    plotRS2(delta, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.025), label=label4)
    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=1),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label4, contour='land')
    plt.close('all')
    a = label4.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure1d_.tiff")
    system("convert -compress lzw /home/mag/Figure1d_.tiff /home/mag/Figure1d_.tiff")


    # Figure 4 - wave breaking contribution
    plotRS2(SigmaWb, lat, lon, pixel, line, \
            scale=scale, m=m, clm=(0,0.08), label=label5)
#    plt.text(x,y,"d",bbox=dict(facecolor='w', alpha=1),stretch='expanded',fontsize=27)
    makeMap(ll_lon, ur_lon, \
            ll_lat, ur_lat, m, name=label5, contour='land')
    plt.close('all')
    a = label5.split(' ')[0] # split the name if it has spaces
    system("rm " + "/home/mag/" + a + ".tiff")
    system("mv " + "/home/mag/" + a + "_ETOPO1.tiff" + " " + "/home/mag/Figure4.tiff")
    system("convert -compress lzw /home/mag/Figure4.tiff /home/mag/Figure4.tiff")