Exemple #1
0
def gdal_save_geotiff(texture, xyz, output_path, epsg=29193):
    import gdal, osr

    driver = gdal.GetDriverByName("GTiff")

    ds = driver.Create(output_path,
                       texture.shape[2],
                       texture.shape[1],
                       texture.shape[0],
                       options=['PHOTOMETRIC=RGB', 'PROFILE=GeoTIFF'])
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(epsg)
    # ds.SetGeoTransform([0, 0, 0, 0, 0, 0])
    # srs.SetFromUserInput('WGS84')
    # srs.SetFromUserInput('EPSG:29193')
    # ds.SetProjection(srs.ExportToWkt())
    #ds.SetGCPs([gdal.GCP(gcp[0][0], gcp[0][1], gcp[0][1], gcp[1][0], gcp[1][1]) for gcp in gcps], ds.GetProjection())
    #ds.SetGCPs([gdal.GCP(gcp[0][0], gcp[0][1], gcp[0][2], gcp[1][0], gcp[1][1]) for gcp in gcps], srs.ExportToWkt())
    # ds.SetGCPs([gdal.GCP(*gcp) for gcp in gcps], srs.ExportToWkt())
    gcps = []
    gcps.append(gdal.GCP(xyz[0][0], xyz[0][1], xyz[0][2], 0, 0))
    gcps.append(gdal.GCP(xyz[1][0], xyz[1][1], xyz[1][2], 1, 0))
    gcps.append(gdal.GCP(xyz[2][0], xyz[2][1], xyz[2][2], 1, 1))
    gcps.append(gdal.GCP(xyz[3][0], xyz[3][1], xyz[3][2], 0, 1))
    ds.SetGCPs(gcps, srs.ExportToWkt())

    for i in range(texture.shape[0]):
        ds.GetRasterBand(i + 1).WriteArray(texture[i, :, :])
    ds.FlushCache()
Exemple #2
0
 def setUpClass(cls):
     print '=============='
     print 'Start georeferencing tests ...'
     print '=============='
     cls.proj = '+proj=longlat +ellps=bessel +datum=potsdam +no_defs'
     cls.dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            '../test-data')
     cls.file = os.path.join(cls.dir, 'test.tif')
     cls.file_vrt = os.path.join(cls.dir, 'test.vrt')
     cls.clip_raster = os.path.join(cls.dir, 'test_georef.tif')
     cls.clip_shp = os.path.join(cls.dir, 'test_shp.shp')
     cls.logger = createLogger('GeoreferenceTest', logging.DEBUG)
     cls.gcps = []
     cls.gcps.append(
         gdal.GCP(21.1666679382324, 55.7999992370605, 0, 7057, 7348))
     cls.gcps.append(
         gdal.GCP(21.1666679382324, 55.9000015258789, 0, 7043, 879))
     cls.gcps.append(
         gdal.GCP(20.9999980926514, 55.7999992370605, 0, 985, 7331))
     cls.gcps.append(
         gdal.GCP(20.9999980926514, 55.9000015258789, 0, 969, 869))
     cls.boundingbox = [[20.9999980926514, 55.7999992370605],
                        [20.9999980926514, 55.9000015258789],
                        [21.1666679382324, 55.9000015258789],
                        [21.1666679382324, 55.7999992370605],
                        [20.9999980926514, 55.7999992370605]]
Exemple #3
0
def get_L1_geomesh(lat_array, lon_array):
    #GCPのリストを作る
    gcp_list = []
    #東経180度西経-180度の線を越えていないかチェック
    top_left_lon = lon_array[0][0]
    top_right_lon = lon_array[0][-1]
    bottom_left_lon = lon_array[-1][0]
    bottom_right_lon = lon_array[-1][-1]

    #東経180度西経-180度の線をまたぐ場合
    if((top_left_lon>top_right_lon) or\
     (top_left_lon>bottom_right_lon) or\
     (bottom_left_lon>top_right_lon) or\
     (bottom_left_lon>bottom_right_lon)\
     ):
        lon_array = np.where(lon_array < 0, lon_array + 360, lon_array)
        for column in range(0, lat_array.shape[0], 20):
            for row in range(0, lat_array.shape[1], 20):
                gcp = gdal.GCP(lon_array[column][row], lat_array[column][row],
                               0, row * 10, column * 10)
                gcp_list.append(gcp)
    #東経180度西経-180度の線をまたがない場合
    else:
        for column in range(0, lat_array.shape[0], 20):
            for row in range(0, lat_array.shape[1], 20):
                gcp = gdal.GCP(lon_array[column][row], lat_array[column][row],
                               0, row * 10, column * 10)
                gcp_list.append(gcp)

    return gcp_list
def correctGCPOffset(gcps, offset):
    """ Function corrects the gcp so that the offset is recognized.

    :type gcps: List<gdal.GCP>
    :type offset: dict<string, integer>
    :return: List<gdal.GCP> """
    response = []
    for gcp in gcps:
        gdal.GCP(9.99999904632568, 48.9000015258789, 0, 637, 652)
        response.append(
            gdal.GCP(gcp.GCPX, gcp.GCPY, gcp.GCPZ,
                     gcp.GCPPixel - offset['left'],
                     gcp.GCPLine - offset['top']))
    return response
Exemple #5
0
    def get_gcps(self, flip_gcp_line=False):
        """ Get Ground Control Points for the dataset. 

        Note that OPeNDAP streams and netCDF files are read differently by gdal. The OPeNDAP streams
        are read by specifying the get parameters to the OPeNDAP url. The get parameters specify the
        reference dimensions, e.g., x and y. Since these are specified, the raster data is correctly
        referenced to the GCPs. However, when gdal reads a raster band from netCDF, it reads it
        "blindly". This is risky, since the definition of origo may be different in gdal vs the
        original data (e.g., first line starts in upper left corner or in lower left corner). For
        Sentinel-1, the raster data is flipped in relation to the GCPs, so we need to flip the GCP
        line vector as well.

        """
        lon = self.ds.variables['GCP_longitude_' + self.ds.polarisation[:2]][:]
        lat = self.ds.variables['GCP_latitude_' + self.ds.polarisation[:2]][:]
        line = self.ds.variables['GCP_line_' + self.ds.polarisation[:2]][:]
        if flip_gcp_line:
            # Flip line vector
            line = self.ds.dimensions['y'].size - line
        pixel = self.ds.variables['GCP_pixel_' + self.ds.polarisation[:2]][:]

        gcps = []
        for i0 in range(0, self.ds.dimensions['gcp_index'].size):
            gcp = gdal.GCP(float(lon[i0]), float(lat[i0]), 0, float(pixel[i0]),
                           float(line[i0]))
            gcps.append(gcp)

        return gcps
Exemple #6
0
 def transform(self, pin):
     # Define output image
     if not self.reverse_order:
         img = pin[0]
         georef = pin[1]
     else:
         img = pin[1]
         georef = pin[0]
     pout = Image(img.data, img.name, img.metadata.copy())
     # Set GCP values
     gcps = []
     root = ET.fromstring(georef)
     gcpentries = root.findall('./geolocationGrid/gridPoint')
     for gcpentry in gcpentries:
         gcps.append(
             gdal.GCP(
                 float(gcpentry.find('lon').text),  #longitude
                 float(gcpentry.find('lat').text),  #latitude
                 float(gcpentry.find('height').text),  #altitude
                 float(gcpentry.find('col').text),  #pixel=column=x
                 float(gcpentry.find('row').text)  #line=row=y
             ))
     pout.metadata['gcps'] = gcps
     # Set GCP projection
     crs = osr.SpatialReference()
     crs.ImportFromEPSG(4326)
     pout.metadata['gcp_projection'] = crs.ExportToWkt()
     return pout
Exemple #7
0
def do_image_geotransform(originalPath,
                          imageMetaData,
                          outputPathTemplate,
                          warning=True):
    if warning:
        print(
            "**** WARNING: in georeference_images.do_image_geotransform(): This makes a strong assumption that the right hand edge of the image is the 'top' of the image."
        )
    #Original incorrect (assumes corners are labelled normally). Also incorrect coordinates.
#    gcps = [gdal.GCP(imageMetaData["refpoint_topleft_lon"], imageMetaData["refpoint_topleft_lat"], 0, 0, 0),
#            gdal.GCP(imageMetaData["refpoint_topright_lon"], imageMetaData["refpoint_topright_lat"], 0, float(imageMetaData["num_pixels_x"]-1), 0),
#            gdal.GCP(imageMetaData["refpoint_bottomleft_lon"], imageMetaData["refpoint_bottomleft_lat"], 0, 0, float(imageMetaData["num_pixels_y"]-1)),
#            gdal.GCP(imageMetaData["refpoint_bottomright_lon"], imageMetaData["refpoint_bottomright_lat"], 0, float(imageMetaData["num_pixels_x"]-1), float(imageMetaData["num_pixels_y"]-1)),
#            ];

#Correct corners correct coordinates (vertical image axis is positive y).
    gcps = [
        gdal.GCP(imageMetaData["refpoint_topleft_lon"],
                 imageMetaData["refpoint_topleft_lat"], 0,
                 float(imageMetaData["num_pixels_x"] - 1),
                 float(imageMetaData["num_pixels_y"] - 1)),
        gdal.GCP(imageMetaData["refpoint_topright_lon"],
                 imageMetaData["refpoint_topright_lat"], 0,
                 float(imageMetaData["num_pixels_x"] - 1), 0),
        gdal.GCP(imageMetaData["refpoint_bottomleft_lon"],
                 imageMetaData["refpoint_bottomleft_lat"], 0, 0,
                 float(imageMetaData["num_pixels_y"] - 1)),
        gdal.GCP(imageMetaData["refpoint_bottomright_lon"],
                 imageMetaData["refpoint_bottomright_lat"], 0, 0, 0),
    ]

    #Make VRT file
    ds = gdal.Open(originalPath, gdal.GA_ReadOnly)
    #ds = gdal.Translate(outputPathTemplate.safe_substitute(EXTENSION="vrt"), ds, outputSRS = 'EPSG:3857', GCPs = gcps, format="VRT")
    ds = gdal.Translate(outputPathTemplate.safe_substitute(EXTENSION="vrt"),
                        ds,
                        outputSRS='EPSG:4326',
                        GCPs=gcps,
                        format="VRT")  #WGS84
    ds = None

    #Warp using GCP points. Using commandline tools because there seems to be a bug which creates a transparent box when using the API
    #cmd = "gdalwarp -s_srs EPSG:4326 -t_srs EPSG:4326 "+outputPathTemplate.safe_substitute(EXTENSION="vrt")+" "+outputPathTemplate.safe_substitute(EXTENSION="tif");
    cmd = "gdalwarp -s_srs EPSG:4326 -t_srs EPSG:4326 " + outputPathTemplate.safe_substitute(
        EXTENSION="vrt") + " " + outputPathTemplate.safe_substitute(
            EXTENSION="tif")
    os.system(cmd)
Exemple #8
0
def parseGcps(georeference):
    gcps = []
    for i in range(0, len(georeference)):
        gcps.append(
            gdal.GCP(georeference[i]['target'][0],
                     georeference[i]['target'][1], 0,
                     georeference[i]['source'][0],
                     georeference[i]['source'][1]))
    return gcps
def CopyDatasetInfo( src, dst, xoff=0, yoff=0 ):
    """
    Copy georeferencing information and metadata from one dataset to another.
    src: input dataset
    dst: output dataset - It can be a ROI -
    xoff, yoff:  dst's offset with respect to src in pixel/line.

    Notes: Destination dataset must have update access.  Certain formats
           do not support creation of geotransforms and/or gcps.

    """

    dst.SetMetadata( src.GetMetadata() )



    #Check for geo transform
    gt = src.GetGeoTransform()
    if gt != (0,1,0,0,0,1):
        dst.SetProjection( src.GetProjectionRef() )

        if (xoff == 0) and (yoff == 0):
            dst.SetGeoTransform( gt  )
        else:
            ngt = [gt[0],gt[1],gt[2],gt[3],gt[4],gt[5]]
            ngt[0] = gt[0] + xoff*gt[1] + yoff*gt[2];
            ngt[3] = gt[3] + xoff*gt[4] + yoff*gt[5];
            dst.SetGeoTransform( ( ngt[0], ngt[1], ngt[2], ngt[3], ngt[4], ngt[5] ) )

    #Check for GCPs
    elif src.GetGCPCount() > 0:

        if (xoff == 0) and (yoff == 0):
            dst.SetGCPs( src.GetGCPs(), src.GetGCPProjection() )
        else:
            gcps = src.GetGCPs()
            #Shift gcps
            new_gcps = []
            for gcp in gcps:
                ngcp = gdal.GCP()
                ngcp.GCPX = gcp.GCPX
                ngcp.GCPY = gcp.GCPY
                ngcp.GCPZ = gcp.GCPZ
                ngcp.GCPPixel = gcp.GCPPixel - xoff
                ngcp.GCPLine = gcp.GCPLine - yoff
                ngcp.Info = gcp.Info
                ngcp.Id = gcp.Id
                new_gcps.append(ngcp)

            try:
                dst.SetGCPs( new_gcps , src.GetGCPProjection() )
            except:
                print("Failed to set GCPs")
                return

    return
def format_gdalgcps(x, y, z, pix, lin):
    """
    """
    sizes = [x.size, y.size, z.size, pix.size, lin.size]
    if min(sizes) != max(sizes):
        raise Exception('All inputs must be of same size.')
    gcps = []
    for i, j, k, l, m in zip(x.flat, y.flat, z.flat, pix.flat, lin.flat):
        gcps.append(gdal.GCP(float(i), float(j), float(k), float(l), float(m)))
    return gcps
Exemple #11
0
def CopyGDALGCP(gcp):
    ngcp = gdal.GCP()
    ngcp.GCPPixel = gcp.GCPPixel
    ngcp.GCPLine = gcp.GCPLine
    ngcp.GCPX = gcp.GCPX
    ngcp.GCPY = gcp.GCPY
    ngcp.GCPZ = gcp.GCPZ
    ngcp.Id = gcp.Id
    ngcp.Info = gcp.Info

    return ngcp
def createGcps(coords):
    gcps = []
    for coord in coords:
        # 'coord' = {'location': [-3.756732387660781, 50.57983418053561], 'pixel': [2164, 966]}
        col = coord['pixel'][0]
        row = coord['pixel'][1]
        x = coord['location'][0]
        y = coord['location'][1]
        z = 0
        gcp = gdal.GCP(x, y, z, col, row)
        gcps.append(gcp)
    return gcps
def parseGcps(georeference):
    """
    :param georeference:  dict
    :return: list.<gdal.GCP>
    """
    gcps = []
    for i in range(0, len(georeference)):
        gcps.append(
            gdal.GCP(georeference[i]['target'][0],
                     georeference[i]['target'][1], 0,
                     georeference[i]['source'][0],
                     georeference[i]['source'][1]))
    return gcps
Exemple #14
0
 def testAddGCPToVRT(self):
     print 'Test if gdal could add gcps to VRT ...'
     out_format = 'VRT'
     dst_file = os.path.join(self.dir, 'test_gcps.vrt')
     dataset = gdal.Open(self.file_vrt, GA_ReadOnly)
     dst_driver = dataset.GetDriver()
     dst_dataset = dst_driver.CreateCopy(dst_file, dataset, 0)
     gcp = gdal.GCP(10, 10, 0, 100, 100)
     dst_dataset.SetGCPs([gcp], self.proj)
     del dst_dataset
     self.assertTrue(os.path.exists(dst_file), 'Could not find vrt file')
     os.remove(dst_file)
     print '=============='
Exemple #15
0
    def get_gcps(self):

        lon = self.ds.variables['GCP_longitude_' + self.ds.polarisation[:2]]
        lat = self.ds.variables['GCP_latitude_' + self.ds.polarisation[:2]]
        line = self.ds.variables['GCP_line_' + self.ds.polarisation[:2]]
        pixel = self.ds.variables['GCP_pixel_' + self.ds.polarisation[:2]]

        gcps = []
        for i0 in range(0, self.ds.dimensions['gcp_index'].size):
            gcp = gdal.GCP(float(lon[i0].data), float(lat[i0].data), 0,
                           float(pixel[i0].data), float(line[i0].data))
            gcps.append(gcp)

        return gcps
Exemple #16
0
    def load_gcps_cb(self, *args):
        """ Load gcps from a text file """
        self.clear_gcps()
        info = getgcpfile()
        if info is None:
            # user pressed cancel
            return
        if ((info[2] is None) or (info[3] is None) or (info[4] is None)
                or (info[5] is None)):
            gvutils.error('Invalid column info for GCP text file!')
            return

        try:
            fh = open(info[0], 'r')
            flines = fh.readlines()
        except:
            gvutils.error('Unable to read GCP text file!')
            return

        idx = 0
        for cline in flines:
            if string.strip(info[1]) == '':
                # whitespace delimited
                sline = string.split(cline)
            else:
                sline = string.split(cline, info[1])
            try:
                gcp = gdal.GCP()
                gcp.GCPPixel = float(string.strip(sline[info[2] - 1]))
                gcp.GCPLine = float(string.strip(sline[info[3] - 1]))
                gcp.GCPX = float(string.strip(sline[info[4] - 1]))
                gcp.GCPY = float(string.strip(sline[info[5] - 1]))
                if info[6] is not None:
                    gcp.GCPZ = float(string.strip(sline[info[6] - 1]))
                if info[7] is not None:
                    gcp.Id = string.strip(sline[info[7] - 1])
                if info[8] is not None:
                    gcp.Info = string.strip(sline[info[8] - 1])
                self.gcplist.append(gcp)
            except:
                # first line might have column names, so
                # ignore errors.  otherwise, report invalid
                # lines
                if idx != 0:
                    print 'Warning: invalid line ' + str(idx) + ' in GCP file!'

            idx = idx + 1

        self.gcpgrid.refresh()
Exemple #17
0
def generateGCPs(lat, lon):
    GCP_list = []
    n_row, n_col = np.shape(lat)

    for i in range(0, n_row - 1):
        GCPPixel = i * 2 + 1
        for j in range(0, n_col - 1):
            lon_gap = lon[i + 1][j] - lon[i][j]
            lat_gap = lat[i][j + 1] - lat[i][j]
            GCPLine = j * 2 + 1
            GCPX = lon[i][j] + lon_gap / 4
            GCPY = lat[i][j] + lat_gap / 4
            gcp = gdal.GCP(GCPX, GCPY, 0, GCPPixel, GCPLine)
            GCP_list.append(gcp)
    return GCP_list
Exemple #18
0
def delete3():
    pass
    tif_path1 = r'E:\NPP\temp\svi01.tif'
    lat_path = r'E:\NPP\temp\Latitude.tif'
    lon_path = r'E:\NPP\temp\Longitude.tif'
    tif_obj1 = GeoTiffFile(lat_path)
    tif_obj1.readTif()
    lat_data = tif_obj1.getBandData(0)
    tif_obj2 = GeoTiffFile(lon_path)
    tif_obj2.readTif()
    lon_data = tif_obj2.getBandData(0)
    dataset = gdal.Open(tif_path1, gdal.GA_Update)
    geo_line = 7680  # 地理信息行数
    geo_sample = 6400  # 地理信息列数

    # 采样间隔
    resample_step = 100
    resample_line_num = int(geo_line / resample_step)
    resample_sample_num = int(geo_sample / resample_step)
    position_list = []
    for i in range(resample_line_num):
        for j in range(resample_sample_num):
            position_list.append(
                ((i + 1) * resample_step - 1, (j + 1) * resample_step - 1))
    gcps_list = []
    for each in position_list:
        lie = each[1]
        hang = each[0]
        lon = float(lon_data[hang][lie])
        lat = float(lat_data[hang][lie])
        gdal_gcp = gdal.GCP(lon, lat, 0, lie, hang)
        gcps_list.append(gdal_gcp)
    sr = osr.SpatialReference()
    sr.SetWellKnownGeogCS('WGS84')
    # 添加控制点
    dataset.SetGCPs(gcps_list, sr.ExportToWkt())

    out_tif_path = r'E:\NPP\temp\svi01_proj.tif.'
    dst_ds = gdal.Warp(out_tif_path,
                       dataset,
                       format='GTiff',
                       tps=True,
                       xRes=0.0037,
                       yRes=0.0037,
                       dstNodata=65533,
                       resampleAlg=gdal.GRIORA_NearestNeighbour,
                       outputType=gdal.GDT_UInt16)
    """
def createGCPs(clipParams, georefCoords, imgHeight):
    """ For a given list of gcps coordinates it creates a list of gdal GCPS.

    :type clipParams: List.<str>
    :type georefCoords: List.<List.<Float>>
    :type imgHeight: int
    :return: List.<gdal.GCP>
    :raise: vkviewer.python.georef.georeferenceexceptions.CreateGCPException """
    try:
        # at first parse pixel coords
        pixels = []
        for point in clipParams.split(","):
            x, y = point.split(":")
            # recalculate the y coordinates because of different coordinates origin
            pixels.append((round(float(x)), imgHeight - round(float(y))))

        # order the list
        xList = []
        yList = []
        for tuple in pixels:
            xList.append(tuple[0])
            yList.append(tuple[1])
        xList.sort()
        yList.sort()
        orderedList = [0, 0, 0, 0]
        for tuple in pixels:
            if (tuple[0] == xList[0] or tuple[0] == xList[1]) and \
                (tuple[1] == yList[2] or tuple[1] == yList[3]):
                orderedList[0] = tuple
            elif (tuple[0] == xList[0] or tuple[0] == xList[1]) and \
                (tuple[1] == yList[0] or tuple[1] == yList[1]):
                orderedList[1] = tuple
            elif (tuple[0] == xList[2] or tuple[0] == xList[3]) and \
                (tuple[1] == yList[0] or tuple[1] == yList[1]):
                orderedList[2] = tuple
            elif (tuple[0] == xList[2] or tuple[0] == xList[3]) and \
                (tuple[1] == yList[2] or tuple[1] == yList[3]):
                orderedList[3] = tuple

        # run the matching
        gcps = []
        for i in range(0, len(orderedList)):
            gcps.append(
                gdal.GCP(georefCoords[i][0], georefCoords[i][1], 0,
                         orderedList[i][0], orderedList[i][1]))
        return gcps
    except:
        raise CreateGCPException('Error while trying to create the GCPs')
Exemple #20
0
def _get_gcps(x_var: xr.DataArray, y_var: xr.DataArray, i_step: int,
              j_step: int) -> List[gdal.GCP]:
    x_values = x_var.values
    y_values = y_var.values
    i_size = x_var.shape[-1]
    j_size = x_var.shape[-2]
    gcps = []
    gcp_id = 0
    i_count = (i_size + i_step - 1) // i_step
    j_count = (j_size + j_step - 1) // j_step
    for j in np.linspace(0, j_size - 1, j_count, dtype=np.int32):
        for i in np.linspace(0, i_size - 1, i_count, dtype=np.int32):
            x, y = float(x_values[j, i]), float(y_values[j, i])
            gcps.append(
                gdal.GCP(x, y, 0.0, i + 0.5, j + 0.5, '%s,%s' % (i, j),
                         str(gcp_id)))
            gcp_id += 1
    return gcps
def set_metadata(source_path, dest_path):
    # Open the file:
    file_name = get_name(source_path)
    source_path = '/vsizip/{0}/{1}.SAFE'.format(source_path, file_name)
    source_ds = gdal.Open(source_path, gdalconst.GA_ReadOnly)
    metadata = source_ds.GetMetadata()
    gcp = source_ds.GetGCPs()
    gcpproj = source_ds.GetGCPProjection()

    ds = gdal.Open(dest_path, gdalconst.GA_Update)

    # resolution from 10m to 50m
    newgcp = [gdal.GCP(tmp.GCPX, tmp.GCPY, tmp.GCPZ, tmp.GCPPixel // 5, tmp.GCPLine // 5) for tmp in gcp]

    # set metadata
    ds.SetGCPs(newgcp, gcpproj)
    ds.SetMetadata(metadata)
    return True
Exemple #22
0
def get_L2_geomesh(filename, lintile, coltile):

    #グラニュールIDからタイル番号を取得する
    #縦方向
    vtile = int(filename[21:23])
    #横方向
    htile = int(filename[23:25])

    #SGLI/L2であれば固定
    #縦方向の総タイル数
    vtilenum = 18
    #横方向の総タイル数
    htilenum = 36

    #緯度方向(dlin)、経度方向(dcol)
    #それぞれの1画素の大きさ
    #d=dlin=dcol
    d = 180.0 / lintile / vtilenum

    #求めたりタイル番号の左上画素の中心の緯度[deg]は、
    #1タイルあたりの角度が10[deg]であることから、
    lat0 = 90.0 - vtile * 10 - d / 2

    #求めたいタイル番号の左上画素の中心の経度[deg]は、
    #1タイルあたりの角度が10[deg]であることから、
    lon0 = -180.0 + htile * 10 + d / 2

    #gdal_translateに与えるGCPのリスト
    gcp_list = []

    for lin in range(0, lintile + 1, 100):
        lat = lat0 - lin * d
        r = np.cos(np.radians(lat))
        for col in range(0, coltile + 1, 100):
            if (lin == lintile):
                lin = lin - 1
            if (col == coltile):
                col = col - 1
            lon = (lon0 + col * d) / r
            gcp = gdal.GCP(round(lon, 6), round(lat, 6), 0, col + 0.5,
                           lin + 0.5)
            gcp_list.append(gcp)

    return gcp_list
Exemple #23
0
def GeoTransformToGCPs(gt,num_pixels,num_lines,grid=2):
    """ Form a gcp list from a geotransform. If grid=0, just use 4
        corners.  If grid=1, split each dimension once.  If grid=2,
        split twice, etc:

        grid=0             grid=1                grid=2

        *           *      *     *     *         *   *   *   *
        
                                                 *   *   *   *    
                           *     *     *
                                                 *   *   *   *
                                               
        *           *      *     *     *         *   *   *   *

        This function is meant to be used to convert a geotransform
        to gcp's so that the geocoded information can be reprojected.

        Inputs: gt- geotransform to convert to gcps
                num_pixels- number of pixels in the dataset
                num_lines- number of lines in the dataset
                grid- see above.  Defaults to 2.
        
    """
    
    gcp_list=[]

    parr=Numeric.arange(0.0,num_pixels+1.0,num_pixels/(grid+1.0))
    larr=Numeric.arange(0.0,num_lines+1.0,num_lines/(grid+1.0))

    for idx in range(len(parr)*len(larr)):
        cgcp=gdal.GCP()
        pix=parr[idx % len(parr)]
        line=larr[idx/len(larr)]
        cgcp.Id=str(idx)
        cgcp.GCPX=gt[0]+(pix*gt[1])+(line*gt[2])
        cgcp.GCPY=gt[3]+(pix*gt[4])+(line*gt[5])
        cgcp.GCPZ=0.0
        cgcp.GCPPixel=pix
        cgcp.GCPLine=line
        
        gcp_list.append(cgcp)

    return gcp_list
def get_gdal_transformer(gcplon, gcplat, gcppixel, gcpline, xsize, ysize):
    """
    """
    gdal.SetCacheMax(2**30)
    gcps = []
    for i, j, k, l in zip(gcplon.flat, gcplat.flat, gcppixel.flat, gcpline.flat):
        gcps.append(gdal.GCP(float(i), float(j), 0., float(k), float(l)))
    srs = osr.SpatialReference()
    srs.SetWellKnownGeogCS('WGS84')
    proj = srs.ExportToWkt()
    drv = gdal.GetDriverByName('MEM')
    dset = drv.Create('tmp', int(xsize), int(ysize))
    #dset = drv.Create(id_generator(), int(xsize), int(ysize))
    dset.SetGCPs(gcps, proj)
    #options = ['']
    #options = ['MAX_GCP_ORDER=3']
    options = ['MAX_GCP_ORDER=-1']
    transformer = gdal.Transformer(dset, None, options)
    return transformer
Exemple #25
0
    def Warp_Raster(self, gcps, BAND_ID, OUTPUT_LOCATION):

        #line1=[]
        try:
            logger.info('WARPING THE IMAGE WITH THE GCPS')
            f = h5py.File(self.h5r_file_location, 'r')
            BAND = f['ImageData'][BAND_ID]
            #input_path = BAND_LOCATION
            output_path = OUTPUT_LOCATION
            # GCP input
            # xyz = [...]
            # row_col = [...]
            band_data = gdal.GetDriverByName('GTiff').Create(
                output_path, BAND.shape[1], BAND.shape[0], 1)
            utm_c = transform_wgs84_to_utm(gcps[0][0], gcps[0][1])
            band_srs = osr.SpatialReference()
            band_data.SetProjection(utm_c[1])
            #print([ utm_c[0][0], 23.5, 0,utm_c[0][1], 0, 23.5 ])
            #band_data.SetGeoTransform( [ utm_c[0][0], 23.5, 0,utm_c[0][1], 0, -23.5 ] )
            #ulx,xres,xskew,tly,skewy,res
            band_data_band = band_data.GetRasterBand(1)
            #outData = numpy.zeros((rows,cols), numpy.int16)
            BAND = np.array(BAND)
            band_data_band.WriteArray(BAND, 0, 0)
            band_data.FlushCache()
            gcps_fin = []
            for gcp in gcps:
                gcps_fin.append(
                    gdal.GCP(gcp[0], gcp[1], gcp[2], gcp[3], gcp[4]))
            #band_data=[]
            warp_with_gcps(band_data,
                           output_path,
                           gcps_fin,
                           gcp_epsg=4326,
                           output_epsg=4326)
            logger.success('WARPING IMAGE COMPLETED USING GCPS. OUTPUT AT ' +
                           output_path)
            return 1
        except Exception as e:
            logger.error("WARPING NOT DONE. RETURNED NONE WITH BELOW ERROR")
            logger.exception(e)
            return None
Exemple #26
0
 def transform(self, pin):
     if not self.reverse_order:
         img = pin[0]
         grid = pin[1]
     else:
         img = pin[1]
         grid = pin[0]
     pout = Image(img.data, img.name, img.metadata.copy())
     if self.row_range is None:
         rlo = 0
         rhi = img.data.shape[1] - 1
     else:
         rlo = self.row_range[0]
         rhi = self.row_range[1]
     if self.col_range is None:
         clo = 0
         chi = img.data.shape[2] - 1
     else:
         clo = self.col_range[0]
         chi = self.col_range[1]
     rspace = self.spacing
     cspace = self.spacing
     if self.row_spacing is not None:
         rspace = self.row_spacing
     if self.col_spacing is not None:
         cspace = self.col_spacing
     gcps = []
     for ri in range(rlo, rhi + 1, rspace):
         for ci in range(clo, chi + 1, cspace):
             gcps.append(
                 gdal.GCP(
                     grid.data[1, ri, ci],  #longitude
                     grid.data[0, ri, ci],  #latitude
                     grid.data[2, ri, ci],  #altitude
                     ci,
                     ri  #pixel=column=x, line=row=y
                 ))
     if len(gcps) > 10922:
         warnings.warn('! Many GCPs generated in CapellaGridToGCPs.')
     pout.metadata['gcps'] = gcps
     return pout
Exemple #27
0
    def getGcps( self, step=20 ):

        """
        get grid of lat / lons as gcps
        """

        # initialise list and dims
        rows, cols = self._geo[ 'longitude' ].shape
        gcps = []

        # loop through lat / lon arrays
        for row in range( 0, rows, step ):
            for col in range( 0, cols, step ):

                # get geo coordinates
                x = self._geo[ 'longitude' ][ row ][ col ]
                y = self._geo[ 'latitude' ][ row ][ col ]
                z = 0.0

                # create gcp
                gcps.append( gdal.GCP( x, y, z, col, row ) )

        return gcps
def own_copy(coreg_info):
    new_dict = {}
    new_dict['GCPList'] = [
        gdal.GCP(gcp_swig_obj.GCPX, gcp_swig_obj.GCPY, gcp_swig_obj.GCPZ,
                 gcp_swig_obj.GCPPixel, gcp_swig_obj.GCPLine)
        for gcp_swig_obj in coreg_info['GCPList']
    ]
    new_dict['mean_shifts_px'] = {
        'x': coreg_info['mean_shifts_px']['x'],
        'y': coreg_info['mean_shifts_px']['y']
    }
    new_dict['mean_shifts_map'] = {
        'x': coreg_info['mean_shifts_map']['x'],
        'y': coreg_info['mean_shifts_map']['y']
    }
    new_dict['updated map info means'] = [
        x for x in coreg_info['updated map info means']
    ]
    new_dict['original map info'] = [
        x for x in coreg_info['original map info']
    ]
    new_dict['reference projection'] = coreg_info['reference projection']
    new_dict['success'] = coreg_info['success']
    new_dict['reference extent'] = {
        'cols': coreg_info['reference extent']['cols'],
        'rows': coreg_info['reference extent']['rows']
    }
    new_dict['reference grid'] = [[
        coreg_info['reference grid'][0][0], coreg_info['reference grid'][0][1]
    ], [
        coreg_info['reference grid'][1][0], coreg_info['reference grid'][1][1]
    ]]
    new_dict['reference geotransform'] = [
        x for x in coreg_info['reference geotransform']
    ]
    return new_dict
def update_gcp_rotation(coreg_dict, inv_rotation_matrix, geotransform,
                        rotation_matrix_warp, save_gcp_flag):
    coreg_dict['updated map info means'][
        3] = geotransform[0] + coreg_dict['mean_shifts_map']['x']
    coreg_dict['updated map info means'][
        4] = geotransform[3] + coreg_dict['mean_shifts_map']['y']

    for item, gcp_swig_obj in enumerate(coreg_dict['GCPList']):
        x, y, z, pixel, line = gcp_swig_obj.GCPX, gcp_swig_obj.GCPY, gcp_swig_obj.GCPZ, gcp_swig_obj.GCPPixel, gcp_swig_obj.GCPLine

        new_pixel, new_line, _ = (inv_rotation_matrix @ rotation_matrix_warp
                                  ) @ np.array([pixel, line, 1])
        if save_gcp_flag:
            # in order to save the dictionary in json, gdal.GCP object is converted to list
            coreg_dict['GCPList'][item] = [
                gcp_swig_obj.GCPX, gcp_swig_obj.GCPY, gcp_swig_obj.GCPZ,
                new_pixel, new_line
            ]
        else:
            # keep gdal.GCP object
            coreg_dict['GCPList'][item] = gdal.GCP(gcp_swig_obj.GCPX,
                                                   gcp_swig_obj.GCPY,
                                                   gcp_swig_obj.GCPZ,
                                                   new_pixel, new_line)
Exemple #30
0
def oneStepGeoreference():
    if request.method == 'POST':
        file = request.files['document']
        data = dict(request.files)
        filename = secure_filename(file.filename)
        fpath = os.path.join(app.config['PUBLIC_UPLOAD_FOLDER'], "onestep",
                             filename)
        file.save(fpath)
        # outpaths
        translate_image = os.path.join(
            os.path.join(app.config['PUBLIC_UPLOAD_FOLDER'], "onestep",
                         "temp" + file.filename))
        warped_image = os.path.join(
            os.path.join(app.config['PUBLIC_UPLOAD_FOLDER'], "onestep",
                         "final.tif"))
        gcpList = []
        #We sould allow for multidimensional arrays ('gcps') as well as API based GCPs ('api_gcps')
        if 'gcps' in data:
            posted_data = json.load(request.files['gcps'])
            for gcp in posted_data['gcps']:
                #Normalize GCPs and append them to gcpList as gdal.GCP
                if gcp[2] < 0:
                    row = gcp[2] * -1
                else:
                    row = gcp[2]
                if gcp[3] < 0:
                    col = gcp[3] * -1
                else:
                    col = gcp[3]
                gcpList.append(gdal.GCP(gcp[0], gcp[1], 0, row, col))

        elif 'api_gcps' in data:
            #Append GCPs to gcpList as gdal.GCP
            posted_data = json.load(request.files['api_gcps'])
            for gcp in posted_data:
                gcpList.append(
                    gdal.GCP(posted_data[gcp]['lat'], posted_data[gcp]['lon'],
                             0, posted_data[gcp]['col'],
                             posted_data[gcp]['row']))

        else:
            return "No GCPs found."
        #Translate using GCPs
        ds = gdal.Open(fpath)
        #Translate the image by adding the translation coefficients to the image headers.
        dsx = gdal.Translate(translate_image,
                             ds,
                             outputSRS='EPSG:4326',
                             GCPs=gcpList)

        #Use the coefficients to warp pixel locations.
        ds2 = gdal.Warp(warped_image,
                        translate_image,
                        dstAlpha=True,
                        dstSRS="EPSG:4326")
        #cleanup
        del ds
        del dsx
        del ds2
        #Return the warped image.
        response = send_file(warped_image,
                             as_attachment=True,
                             attachment_filename='server.tif')
        return response