示例#1
0
def test_gdal_translate_lib_8():

    gcpList = [
        gdal.GCP(440720.000, 3751320.000, 0, 0, 0),
        gdal.GCP(441920.000, 3751320.000, 0, 20, 0),
        gdal.GCP(441920.000, 3750120.000, 0, 20, 20),
        gdal.GCP(440720.000, 3750120.000, 0, 0, 20)
    ]
    ds = gdal.Open('../gcore/data/byte.tif')
    ds = gdal.Translate('tmp/test8.tif',
                        ds,
                        outputSRS='EPSG:26711',
                        GCPs=gcpList)
    if ds is None:
        return 'fail'

    if ds.GetRasterBand(1).Checksum() != 4672:
        gdaltest.post_reason('Bad checksum')
        return 'fail'

    gcps = ds.GetGCPs()
    if len(gcps) != 4:
        gdaltest.post_reason('GCP count wrong.')
        return 'fail'

    if ds.GetGCPProjection().find('26711') == -1:
        gdaltest.post_reason('Bad GCP projection.')
        return 'fail'

    ds = None

    return 'success'
示例#2
0
def warp_39():

    # Create an output file with GCPs.
    out_file = 'tmp/warp_39.tif'
    ds = gdal.GetDriverByName('GTiff').Create(out_file, 50, 50, 3)

    gcp_list = [
        gdal.GCP(397000, 5642000, 0, 0, 0),
        gdal.GCP(397000, 5641990, 0, 0, 50),
        gdal.GCP(397010, 5642000, 0, 50, 0),
        gdal.GCP(397010, 5641990, 0, 50, 50),
        gdal.GCP(397005, 5641995, 0, 25, 25),
    ]
    ds.SetGCPs(gcp_list, gdaltest.user_srs_to_wkt('EPSG:32632'))
    ds = None

    gdal.Warp(out_file, 'data/test3658.tif', options='-to DST_METHOD=GCP_TPS')

    ds = gdal.Open(out_file)
    cs = ds.GetRasterBand(1).Checksum()
    ds = None

    # Should exactly match the source file.
    exp_cs = 30546
    if cs != exp_cs:
        gdaltest.post_reason('Got %d instead of expected checksum %d.' %
                             (cs, exp_cs))
        return 'fail'

    os.unlink(out_file)
    return 'success'
示例#3
0
def offset_image(inImage, coner_col_row, coner_coord, temp1, temp2):
    '''
    根据影像的脚点行列号及坐标,对影像进行偏移(配准)
    :param inImage:输入影像路径
    :param coner_col_row:元组,(upperLeft_col_row, lowerLeft_col_row, lowerRight_col_row, upperRight_col_row)
    :param coner_coord:元组,(upperLeft_xy, lowerLeft_xy, lowerRight_xy, upperRight_xy)
    '''
    # gdal.GCP()是gdal中地面控制点的数据结构,顺序依次是:空间位置x,y,z,影像列号,行号
    coordlist = [
        gdal.GCP(coner_coord[0][0], coner_coord[0][1], 0, coner_col_row[0][0],
                 coner_col_row[0][1]),
        gdal.GCP(coner_coord[1][0], coner_coord[1][1], 0, coner_col_row[1][0],
                 coner_col_row[1][1]),
        gdal.GCP(coner_coord[2][0], coner_coord[2][1], 0, coner_col_row[2][0],
                 coner_col_row[2][1]),
        gdal.GCP(coner_coord[3][0], coner_coord[3][1], 0, coner_col_row[3][0],
                 coner_col_row[3][1])
    ]

    # 根据脚点坐标进行配准
    gdal.Translate(temp1, inImage, GCPs=coordlist)
    gdal.Warp(temp2,
              temp1,
              format="MEM",
              srcNodata=0.0,
              dstNodata=0.0,
              dstSRS="EPSG:4326")
def test_gdalwarp_lib_5():

    ds = gdal.Open('../gcore/data/byte.tif')
    gcpList = [
        gdal.GCP(440720.000, 3751320.000, 0, 0, 0),
        gdal.GCP(441920.000, 3751320.000, 0, 20, 0),
        gdal.GCP(441920.000, 3750120.000, 0, 20, 20),
        gdal.GCP(440720.000, 3750120.000, 0, 0, 20)
    ]
    ds1 = gdal.Translate('tmp/testgdalwarp_gcp.tif',
                         ds,
                         outputSRS='EPSG:26711',
                         GCPs=gcpList)
    dstDS = gdal.Warp('', ds1, format='MEM', tps=True)

    if dstDS.GetRasterBand(1).Checksum() != 4672:
        gdaltest.post_reason('Bad checksum')
        return 'fail'

    if not gdaltest.geotransform_equals(ds.GetGeoTransform(),
                                        dstDS.GetGeoTransform(), 1e-9):
        gdaltest.post_reason('Bad geotransform')
        return 'fail'

    dstDS = None

    return 'success'
示例#5
0
def SetGCPsToGeoTransform(cornerPointUL, cornerPointUR, cornerPointLR,
                          cornerPointLL, frameCenterLon, frameCenterLat, ele):
    ''' Make Geotranform from pixel to lon lat coordinates '''
    gcps = []

    global gcornerPointUL, gcornerPointUR, gcornerPointLR, gcornerPointLL, gframeCenterLat, gframeCenterLon, geotransform_affine, geotransform

    # TEMP FIX : If have elevation the geotransform is wrong
    if ele:
        del cornerPointUL[-1]
        del cornerPointUR[-1]
        del cornerPointLR[-1]
        del cornerPointLL[-1]

    gcornerPointUL = cornerPointUL
    gcornerPointUR = cornerPointUR
    gcornerPointLR = cornerPointLR
    gcornerPointLL = cornerPointLL

    gframeCenterLat = frameCenterLat
    gframeCenterLon = frameCenterLon

    Height = GetFrameCenter()[2]

    gcp = gdal.GCP(cornerPointUL[1], cornerPointUL[0], Height, 0, 0,
                   "Corner Upper Left", "1")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointUR[1], cornerPointUR[0], Height, xSize, 0,
                   "Corner Upper Right", "2")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLR[1], cornerPointLR[0], Height, xSize, ySize,
                   "Corner Lower Right", "3")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLL[1], cornerPointLL[0], Height, 0, ySize,
                   "Corner Lower Left", "4")
    gcps.append(gcp)
    gcp = gdal.GCP(frameCenterLon, frameCenterLat, Height, xSize / 2,
                   ySize / 2, "Center", "5")
    gcps.append(gcp)

    geotransform_affine = gdal.GCPsToGeoTransform(gcps)

    src = np.float64(
        np.array([[0.0, 0.0], [xSize, 0.0], [xSize, ySize], [0.0, ySize]]))
    dst = np.float64(
        np.array([cornerPointUL, cornerPointUR, cornerPointLR, cornerPointLL]))

    try:
        geotransform = from_points(src, dst)
    except Exception:
        pass

    if geotransform is None:
        qgsu.showUserAndLogMessage("",
                                   "Unable to extract a geotransform.",
                                   onlyLog=True)

    return
示例#6
0
def SetGCPsToGeoTransform(cornerPointUL, cornerPointUR, cornerPointLR,
                          cornerPointLL, frameCenterLon, frameCenterLat, ele):
    ''' Make Geotranform from pixel to lon lat coordinates '''
    gcps = []
    gv.setCornerUL(cornerPointUL)
    gv.setCornerUR(cornerPointUR)
    gv.setCornerLR(cornerPointLR)
    gv.setCornerLL(cornerPointLL)
    gv.setFrameCenter(frameCenterLat, frameCenterLon)

    xSize = gv.getXSize()
    ySize = gv.getYSize()

    Height = GetFrameCenter()[2]

    gcp = gdal.GCP(cornerPointUL[1], cornerPointUL[0], Height, 0, 0,
                   "Corner Upper Left", "1")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointUR[1], cornerPointUR[0], Height, xSize, 0,
                   "Corner Upper Right", "2")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLR[1], cornerPointLR[0], Height, xSize, ySize,
                   "Corner Lower Right", "3")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLL[1], cornerPointLL[0], Height, 0, ySize,
                   "Corner Lower Left", "4")
    gcps.append(gcp)
    gcp = gdal.GCP(frameCenterLon, frameCenterLat, Height, xSize / 2,
                   ySize / 2, "Center", "5")
    gcps.append(gcp)

    at = gdal.GCPsToGeoTransform(gcps)
    gv.setAffineTransform(at)

    src = np.float64(
        np.array([[0.0, 0.0], [xSize, 0.0], [xSize, ySize], [0.0, ySize],
                  [xSize / 2.0, ySize / 2.0]]))
    dst = np.float64(
        np.array([[cornerPointUL[0], cornerPointUL[1]],
                  [cornerPointUR[0], cornerPointUR[1]],
                  [cornerPointLR[0], cornerPointLR[1]],
                  [cornerPointLL[0], cornerPointLL[1]],
                  [frameCenterLat, frameCenterLon]]))

    try:
        geotransform, _ = findHomography(src, dst)
        gv.setTransform(geotransform)
    except Exception:
        pass

    if geotransform is None:
        qgsu.showUserAndLogMessage("",
                                   "Unable to extract a geotransform.",
                                   onlyLog=True)

    return
def do_rgs(data_time_value, rgs_file_path):
    """ 配准
    :param data_time_value: dict 原始图像的信息-GCJ02
        {
            "time" : "",          #时间
            "timestamp" : "",     #时间戳
            "url" : "",           #下载链接
            "extent" : "",        #范围
            "req_pnt" : "",       #该瓦片请求的点坐标
            "file_path" : ""      #文件的path
        }
    :param rgs_file_path: str 配准后保存的路径
    :return: rgs_data_item: dict/None
        {
            "extent" : "", #范围-WGS84
            "file_path" : "", #该文件的路径
        }
    """
    # 将tiff保存到配准文件夹
    origin_file_path = data_time_value["file_path"]
    im = Image.open(origin_file_path)
    im.save(rgs_file_path)

    # 转换extent
    extent_gcj02 = data_time_value[
        "extent_gcj02"]  #[21.532796186275732, 115.14559029127062, 25.66504821372427, 119.65495970872936]
    extent_wgs84 = gcj02towgs84_extent(
        extent_gcj02
    )  #[21.53519080438208, 115.14078044126353, 25.66805217057752, 119.65050502755392]
    x1, y1, x2, y2 = extent_wgs84

    # 用extent_wgs84对rgs_file_path文件进行配准
    ds = gdal.Open(rgs_file_path, gdal.GA_Update)  #打开影像
    if not ds:
        return None
    # 创建坐标系
    srs = osr.SpatialReference()
    srs.SetWellKnownGeogCS('WGS84')
    # 相关信息
    rows = ds.RasterYSize  # 行数
    cols = ds.RasterXSize  # 列数

    # 创建地面控制点:经度、纬度、z,照片列数,照片行数
    gcps = [
        gdal.GCP(y1, x2, 0, 0, 0),  # 左上
        gdal.GCP(y2, x2, 0, cols - 1, 0),  # 右上
        gdal.GCP(y1, x1, 0, 0, rows - 1),  # 左下
        gdal.GCP(y2, x1, 0, cols - 1, rows - 1)  # 右下
    ]
    ds.SetGCPs(gcps, srs.ExportToWkt())
    ds.SetProjection(srs.ExportToWkt())
    ds.SetGeoTransform(gdal.GCPsToGeoTransform(gcps))
    del ds

    return {"extent": extent_wgs84, "file_path": rgs_file_path}
示例#8
0
def vrtwarp_7():

    if test_cli_utilities.get_gdalwarp_path() is None:
        return 'skip'

    src_ds = gdal.Open('../gcore/data/byte.tif')
    tmp_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vrtwarp_7.tif',
                                                      src_ds)
    cs_main = tmp_ds.GetRasterBand(1).Checksum()
    tmp_ds.SetGeoTransform([0, 1, 0, 0, 0, 1])  # cancel geotransform
    gcp1 = gdal.GCP()
    gcp1.GCPPixel = 0
    gcp1.GCPLine = 0
    gcp1.GCPX = 440720.000
    gcp1.GCPY = 3751320.000
    gcp2 = gdal.GCP()
    gcp2.GCPPixel = 0
    gcp2.GCPLine = 20
    gcp2.GCPX = 440720.000
    gcp2.GCPY = 3750120.000
    gcp3 = gdal.GCP()
    gcp3.GCPPixel = 20
    gcp3.GCPLine = 0
    gcp3.GCPX = 441920.000
    gcp3.GCPY = 3751320.000
    src_gcps = (gcp1, gcp2, gcp3)
    tmp_ds.SetGCPs(src_gcps, src_ds.GetProjectionRef())
    tmp_ds.BuildOverviews('NEAR', overviewlist=[2, 4])
    cs_ov0 = tmp_ds.GetRasterBand(1).GetOverview(0).Checksum()
    cs_ov1 = tmp_ds.GetRasterBand(1).GetOverview(1).Checksum()
    tmp_ds = None

    gdaltest.runexternal(
        test_cli_utilities.get_gdalwarp_path() +
        ' tmp/vrtwarp_7.tif tmp/vrtwarp_7.vrt -overwrite -of VRT -tps')

    vrtwarp_ds = gdal.Open('tmp/vrtwarp_7.vrt')
    if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 2:
        gdaltest.post_reason('fail')
        return 'fail'
    if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main:
        print(cs_main)
        return 'fail'
    if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != cs_ov0:
        gdaltest.post_reason('fail')
        return 'fail'
    if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != cs_ov1:
        gdaltest.post_reason('fail')
        return 'fail'
    vrtwarp_ds = None

    gdal.Unlink('tmp/vrtwarp_7.vrt')
    gdal.Unlink('tmp/vrtwarp_7.tif')

    return 'success'
示例#9
0
def geographic_info(ds, srsout=None):
    # Read geotransform matrix and source reference system
    srs = osr.SpatialReference()
    if ds.GetGCPCount():
        gcps = ds.GetGCPs()
        srs.ImportFromWkt(ds.GetGCPProjection())
        geomatrix = gdal.GCPsToGeoTransform(gcps)
    else:
        gcps = []
        if not ds.GetProjection():
            raise ValueError('no geographic info in "%s"' %
                                                        ds.GetDescription())
        srs.ImportFromWkt(ds.GetProjection())
        geomatrix = ds.GetGeoTransform()

    if geomatrix == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
        raise ValueError('no geographic info in "%s"' % ds.GetDescription())

    # Set the target reference system
    srsout = makesrs(srsout)

    # Instantiate the coordinate transformer
    transformer = osr.CoordinateTransformation(srs, srsout)

    # dataset corners setup
    corners = []
    for id_, (pixel, line) in enumerate((
                                (0,                  0),
                                (0,                  ds.RasterYSize - 1),
                                (ds.RasterXSize - 1, ds.RasterYSize - 1),
                                (ds.RasterXSize - 1, 0))):

        X = geomatrix[0] + geomatrix[1] * pixel + geomatrix[2] * line
        Y = geomatrix[3] + geomatrix[4] * pixel + geomatrix[5] * line

        # Shift to the center of the pixel
        X += geomatrix[1] / 2.0
        Y += geomatrix[5] / 2.0
        Z = 0.

        (x, y, z) = transformer.TransformPoint(X, Y, Z)

        gcp = gdal.GCP(x, y, z, pixel, line, '', str(id_ + 1))
        corners.append(gcp)

    # convert GCPs to the targer srs
    outgcps = []
    for gcp in gcps:
        (x, y, z) = transformer.TransformPoint(gcp.GCPX, gcp.GCPY, gcp.GCPZ)
        gcp = gdal.GCP(x, y, z, gcp.GCPPixel, gcp.GCPLine, gcp.Info, gcp.Id)
        outgcps.append(gcp)

    return corners, outgcps
示例#10
0
def SetGCPsToGeoTransform(cornerPointUL, cornerPointUR, cornerPointLR,
                          cornerPointLL, frameCenterLon, frameCenterLat):
    ''' Make Geotranform from pixel to lon lat coordinates '''
    gcps = []

    global gcornerPointUL
    gcornerPointUL = cornerPointUL
    global gcornerPointUR
    gcornerPointUR = cornerPointUR
    global gcornerPointLR
    gcornerPointLR = cornerPointLR
    global gcornerPointLL
    gcornerPointLL = cornerPointLL
    global gframeCenterLat
    gframeCenterLat = frameCenterLat
    global gframeCenterLon
    gframeCenterLon = frameCenterLon
    global geotransform
    global geotransform_affine

    Height = GetFrameCenter()[2]

    gcp = gdal.GCP(cornerPointUL[1], cornerPointUL[0], Height, 0, 0,
                   "Corner Upper Left", "1")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointUR[1], cornerPointUR[0], Height, xSize, 0,
                   "Corner Upper Right", "2")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLR[1], cornerPointLR[0], Height, xSize, ySize,
                   "Corner Lower Right", "3")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLL[1], cornerPointLL[0], Height, 0, ySize,
                   "Corner Lower Left", "4")
    gcps.append(gcp)
    gcp = gdal.GCP(frameCenterLon, frameCenterLat, Height, xSize / 2,
                   ySize / 2, "Center", "5")
    gcps.append(gcp)

    geotransform_affine = gdal.GCPsToGeoTransform(gcps)

    src = np.float64(
        np.array([[0.0, 0.0], [xSize, 0.0], [xSize, ySize], [0.0, ySize]]))
    dst = np.float64(
        np.array([cornerPointUL, cornerPointUR, cornerPointLR, cornerPointLL]))
    geotransform = from_points(src, dst)

    if geotransform is None:
        qgsu.showUserAndLogMessage("",
                                   "Unable to extract a geotransform.",
                                   onlyLog=True)

    return
示例#11
0
文件: vrtwarp.py 项目: plkms/gdal
def vrtwarp_6():

    src_ds = gdal.Open('../gcore/data/byte.tif')
    tmp_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vrtwarp_6.tif',
                                                      src_ds)
    cs_main = tmp_ds.GetRasterBand(1).Checksum()
    tmp_ds.SetGeoTransform([0, 1, 0, 0, 0, 1])  # cancel geotransform
    gcp1 = gdal.GCP()
    gcp1.GCPPixel = 0
    gcp1.GCPLine = 0
    gcp1.GCPX = 440720.000
    gcp1.GCPY = 3751320.000
    gcp2 = gdal.GCP()
    gcp2.GCPPixel = 0
    gcp2.GCPLine = 20
    gcp2.GCPX = 440720.000
    gcp2.GCPY = 3750120.000
    gcp3 = gdal.GCP()
    gcp3.GCPPixel = 20
    gcp3.GCPLine = 0
    gcp3.GCPX = 441920.000
    gcp3.GCPY = 3751320.000
    src_gcps = (gcp1, gcp2, gcp3)
    tmp_ds.SetGCPs(src_gcps, src_ds.GetProjectionRef())
    tmp_ds.BuildOverviews('NEAR', overviewlist=[2, 4])
    cs_ov0 = tmp_ds.GetRasterBand(1).GetOverview(0).Checksum()
    cs_ov1 = tmp_ds.GetRasterBand(1).GetOverview(1).Checksum()

    vrtwarp_ds = gdal.AutoCreateWarpedVRT(tmp_ds)
    vrtwarp_ds.SetDescription('tmp/vrtwarp_6.vrt')
    vrtwarp_ds = None
    tmp_ds = None

    vrtwarp_ds = gdal.Open('tmp/vrtwarp_6.vrt')

    if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 2:
        gdaltest.post_reason('fail')
        return 'fail'
    if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main:
        gdaltest.post_reason('fail')
        return 'fail'
    if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != cs_ov0:
        gdaltest.post_reason('fail')
        return 'fail'
    if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != cs_ov1:
        gdaltest.post_reason('fail')
        return 'fail'

    gdal.Unlink('tmp/vrtwarp_6.vrt')
    gdal.Unlink('tmp/vrtwarp_6.tif')

    return 'success'
示例#12
0
def test_kea_7():
    if gdaltest.kea_driver is None:
        pytest.skip()

    sr = osr.SpatialReference()
    sr.ImportFromEPSG(4326)

    # Geotransform
    ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1)
    assert ds.GetGCPCount() == 0
    assert ds.SetGeoTransform([1, 2, 3, 4, 5, 6]) == 0
    assert ds.SetProjection(sr.ExportToWkt()) == 0
    ds = None

    ds = gdal.Open('tmp/out.kea')
    out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds)
    ds = None
    assert out2_ds.GetGCPCount() == 0
    assert out2_ds.GetGeoTransform() == (1, 2, 3, 4, 5, 6)
    assert out2_ds.GetProjectionRef() != ''
    out2_ds = None

    gdaltest.kea_driver.Delete('tmp/out.kea')
    gdaltest.kea_driver.Delete('tmp/out2.kea')

    # GCP
    ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1)
    gcp1 = gdal.GCP(0, 1, 2, 3, 4)
    gcp1.Id = "id"
    gcp1.Info = "info"
    gcp2 = gdal.GCP(0, 1, 2, 3, 4)
    gcps = [gcp1, gcp2]
    ds.SetGCPs(gcps, sr.ExportToWkt())
    ds = None

    ds = gdal.Open('tmp/out.kea')
    out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds)
    ds = None

    assert out2_ds.GetGCPCount() == 2
    assert out2_ds.GetGCPProjection() != ''
    got_gcps = out2_ds.GetGCPs()
    for i in range(2):
        assert (got_gcps[i].GCPX == gcps[i].GCPX and got_gcps[i].GCPY == gcps[i].GCPY and \
           got_gcps[i].GCPZ == gcps[i].GCPZ and got_gcps[i].GCPPixel == gcps[i].GCPPixel and \
           got_gcps[i].GCPLine == gcps[i].GCPLine and got_gcps[i].Id == gcps[i].Id and \
           got_gcps[i].Info == gcps[i].Info)
    out2_ds = None

    gdaltest.kea_driver.Delete('tmp/out.kea')
    gdaltest.kea_driver.Delete('tmp/out2.kea')
示例#13
0
def overviewds_3():

    src_ds = gdal.Open('data/byte.tif')
    ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/byte.tif', src_ds)
    ds.SetGeoTransform([0, 1, 0, 0, 0, 1])  # cancel geotransform
    gcp1 = gdal.GCP()
    gcp1.GCPPixel = 0
    gcp1.GCPLine = 0
    gcp1.GCPX = 440720.000
    gcp1.GCPY = 3751320.000
    gcp2 = gdal.GCP()
    gcp2.GCPPixel = 0
    gcp2.GCPLine = 20
    gcp2.GCPX = 440720.000
    gcp2.GCPY = 3750120.000
    gcp3 = gdal.GCP()
    gcp3.GCPPixel = 20
    gcp3.GCPLine = 0
    gcp3.GCPX = 441920.000
    gcp3.GCPY = 3751320.000
    src_gcps = (gcp1, gcp2, gcp3)
    ds.SetGCPs(src_gcps, src_ds.GetProjectionRef())

    tr = gdal.Transformer(ds, None, ['METHOD=GCP_POLYNOMIAL'])
    (_, ref_pnt) = tr.TransformPoint(0, 20, 10)

    ds.BuildOverviews('NEAR', overviewlist=[2, 4])
    ds = None

    ds = gdal.OpenEx('tmp/byte.tif', open_options=['OVERVIEW_LEVEL=0'])
    gcps = ds.GetGCPs()
    for i in range(3):
        if gcps[i].GCPPixel != src_gcps[i].GCPPixel / 2 or gcps[i].GCPLine != src_gcps[i].GCPLine / 2 or \
           gcps[i].GCPX != src_gcps[i].GCPX or gcps[i].GCPY != src_gcps[i].GCPY:
            gdaltest.post_reason('fail')
            return 'fail'

    # Really check that the transformer works
    tr = gdal.Transformer(ds, None, ['METHOD=GCP_POLYNOMIAL'])
    (_, pnt) = tr.TransformPoint(0, 20 / 2.0, 10 / 2.0)

    for i in range(3):
        if abs(ref_pnt[i] - pnt[i]) > 1e-5:
            gdaltest.post_reason('fail')
            print(ref_pnt)
            print(pnt)
            return 'fail'
    ds = None

    return 'success'
示例#14
0
    def processImages(self, layerWMS, webScaleParamList, outputFolder):
        scaleFeaturesDict = self.featuresByScale[self.scaleSelected]
        width, height, ncol, nrow = webScaleParamList

        for feat in scaleFeaturesDict.keys():
            bboxStr = scaleFeaturesDict[feat].asWktCoordinates().replace(
                ',', '').split(' ')
            bbox = []
            for i in bboxStr:
                bbox.append(float(i))
            temp_path = tempfile.TemporaryDirectory()
            complete_image = Image.new('RGB', (width * ncol, height * nrow))
            dx = (bbox[2] - bbox[0]) / ncol
            dy = (bbox[3] - bbox[1]) / nrow

            for column in range(ncol):
                xmin = bbox[0] + dx * column
                xmax = bbox[0] + dx * (column + 1)
                for line in range(nrow):
                    ymin = bbox[3] - dy * (line + 1)
                    ymax = bbox[3] - dy * line
                    imageURL = "https://bdgex.eb.mil.br/mapcache?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&BBOX={},{},{},{}&SRS=EPSG:4326&WIDTH={}&HEIGHT={}&LAYERS={}&STYLES=,,,&FORMAT=image/png&DPI=96&MAP_RESOLUTION=96&FORMAT_OPTIONS=dpi:96&TRANSPARENT=TRUE".format(
                        xmin, ymin, xmax, ymax, width, height, layerWMS)
                    partialImage = requests.get(imageURL, allow_redirects=True)
                    temp_file = os.path.join(temp_path.name, 'temp_image.png')
                    open(temp_file, "wb").write(partialImage.content)
                    complete_image.paste(Image.open(temp_file),
                                         (width * column, height * line))

            complete_image.save(
                os.path.join(temp_path.name, 'complete_image.png'))
            outputFile = os.path.join(outputFolder, feat + ".tif")

            p1 = gdal.GCP(bbox[0], bbox[1], 0, 0, height * nrow)
            p2 = gdal.GCP(bbox[2], bbox[1], 0, width * ncol, height * nrow)
            p3 = gdal.GCP(bbox[0], bbox[3], 0, 0, 0)
            p4 = gdal.GCP(bbox[2], bbox[3], 0, width * ncol, 0)

            opt = gdal.TranslateOptions(format='GTiff', GCPs=[p1, p2, p3, p4])
            gdal.Translate(outputFile,
                           os.path.join(temp_path.name, 'complete_image.png'),
                           options=opt)
            temp_path.cleanup()
            processing.run("gdal:assignprojection", {
                'INPUT': outputFile,
                'CRS': "EPSG:4326"
            })

        return
def test_gdal_translate_lib_8():

    gcpList = [gdal.GCP(440720.000, 3751320.000, 0, 0, 0), gdal.GCP(441920.000, 3751320.000, 0, 20, 0), gdal.GCP(441920.000, 3750120.000, 0, 20, 20), gdal.GCP(440720.000, 3750120.000, 0, 0, 20)]
    ds = gdal.Open('../gcore/data/byte.tif')
    ds = gdal.Translate('tmp/test8.tif', ds, outputSRS='EPSG:26711', GCPs=gcpList)
    assert ds is not None

    assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum'

    gcps = ds.GetGCPs()
    assert len(gcps) == 4, 'GCP count wrong.'

    assert ds.GetGCPProjection().find('26711') != -1, 'Bad GCP projection.'

    ds = None
示例#16
0
        def executeTask(task, gcps, projection, records):
            """
            threading function for computing reprojection of point subset 
            """

            # get geographic and tm projection objects
            srs_s = Proj(init=projection['source'])
            srs_t = Proj(init=projection['target'])
            gcps_warp = []

            # process subset of gcp list
            idx = task['offset']
            num_gcps = len(gcps['pixel'])
            count = 0
            while idx <= (task['offset'] + task['items']) and idx < num_gcps:

                # reproject coordinates from source to target srs
                x, y, z = transform(srs_s, srs_t, gcps['X'][idx],
                                    gcps['Y'][idx], gcps['Z'][idx])

                gcps_warp.append(
                    gdal.GCP(x, y, z, gcps['pixel'][idx], gcps['line'][idx]))
                idx = idx + 1
                count = count + 1

            # copy to shared array
            records[task['index']] = gcps_warp

            return
示例#17
0
    def to_GCPList(self):
        # get copy of tie points grid without no data
        try:
            GDF = self.CoRegPoints_table.loc[self.CoRegPoints_table.ABS_SHIFT != self.outFillVal, :].copy()
        except AttributeError:
            # self.CoRegPoints_table has no attribute 'ABS_SHIFT' because all points have been excluded
            return []

        if getattr(GDF, 'empty'):  # GDF.empty returns AttributeError
            return []
        else:
            # exclude all points flagged as outliers
            if 'OUTLIER' in GDF.columns:
                GDF = GDF[GDF.OUTLIER.__eq__(False)].copy()
            avail_TP = len(GDF)

            if not avail_TP:
                # no point passed all validity checks
                return []

            if avail_TP > 7000:
                GDF = GDF.sample(7000)
                warnings.warn('By far not more than 7000 tie points can be used for warping within a limited '
                              'computation time (due to a GDAL bottleneck). Thus these 7000 points are randomly chosen '
                              'out of the %s available tie points.' % avail_TP)

            # calculate GCPs
            GDF['X_UTM_new'] = GDF.X_UTM + GDF.X_SHIFT_M
            GDF['Y_UTM_new'] = GDF.Y_UTM + GDF.Y_SHIFT_M
            GDF['GCP'] = GDF.apply(lambda GDF_row: gdal.GCP(GDF_row.X_UTM_new, GDF_row.Y_UTM_new, 0,
                                                            GDF_row.X_IM, GDF_row.Y_IM), axis=1)
            self.GCPList = GDF.GCP.tolist()

            return self.GCPList
示例#18
0
    def offset_image(self, inImage, outImage, list_col_row, list_xy):
        '''
        根据影像的行列号及对应坐标,对影像进行偏移
        :param inImage: 输入影像路径
        :param outImage: 输入影像路径
        :param list_col_row: 行列号的列表(元组)
        :param list_xy: xy坐标的列表(元组
        :return: 无返回值
        '''
        #gdal.GCP()是gdal中地面控制点的数据结构,顺序依次是:空间位置x,y,z,影像列号,行号
        coordlist = []
        if len(list_col_row) == len(list_xy):
            print("构建GCPs列表......")
            for i in range(len(list_col_row)):
                coordlist.append(
                    gdal.GCP(list_xy[i][0], list_xy[i][1], 0,
                             list_col_row[i][0], list_col_row[i][1]))

            # 根据脚点坐标进行配准
            print("为影像写入GCPs......")
            gdal.Translate("TempOut1.tif", inImage, GCPs=coordlist)
            print("终极变换!")
            gdal.Warp(outImage,
                      "TempOut1.tif",
                      format="GTiff",
                      srcNodata=0.0,
                      dstNodata=0.0,
                      dstSRS="EPSG:4326")
        else:
            print("行列号与xy坐标对数量不匹配,请检查!")
示例#19
0
def test_envi_gcp():

    filename = '/vsimem/test_envi_gcp.dat'
    ds = gdal.GetDriverByName('ENVI').Create(filename, 1, 1)
    gcp = gdal.GCP()
    gcp.GCPPixel = 1
    gcp.GCPLine = 2
    gcp.GCPX = 3
    gcp.GCPY = 4
    ds.SetGCPs([gcp], None)
    ds = None
    gdal.Unlink(filename + ".aux.xml")

    ds = gdal.Open(filename)
    assert ds.GetGCPCount() == 1
    gcps = ds.GetGCPs()
    assert len(gcps) == 1
    gcp = gcps[0]
    ds = None
    assert gcp.GCPPixel == 1
    assert gcp.GCPLine == 2
    assert gcp.GCPX == 3
    assert gcp.GCPY == 4

    gdal.GetDriverByName('ENVI').Delete(filename)
示例#20
0
    def convert(self):
        options=self.map.options

        if options.after_name:
            name_patt=self.name
        elif options.after_map:
            name_patt=self.map.file
        else:
            name_patt=self.img_file
        base = dst_path(name_patt, options.dst_dir)
        if options.long_name:
            base += ' - ' +  "".join([c for c in self.name
                                if c .isalpha() or c.isdigit() or c in '-_.() '])
        dst_dir=os.path.split(base)[0]
        out_format='VRT'
        ext='.'+out_format.lower()

        try:
            start_dir=os.getcwd()
            if dst_dir:
                os.chdir(dst_dir)

            dst_file = os.path.abspath(os.path.basename(base+ext)) # output file
            dst_drv = gdal.GetDriverByName(out_format)
            dst_ds = dst_drv.CreateCopy(
                dst_file.encode(locale.getpreferredencoding()),
                self.raster_ds,
                0
            )
            dst_ds.SetProjection(self.srs)

            #double x = 0.0, double y = 0.0, double z = 0.0, double pixel = 0.0,
            #double line = 0.0, char info = "", char id = ""
            gcps=[gdal.GCP(c[0],c[1],0,p[0],p[1],'',i) for i,p,c in self.refs]
            dst_ds.SetGCPs(gcps,self.refs.srs())
            dst_geotr=gdal.GCPsToGeoTransform(gcps) # if len(gcps) < 5 else (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
            dst_ds.SetGeoTransform(dst_geotr)
            poly,gmt_data=self.cut_poly(dst_ds)
            if poly:
                dst_ds.SetMetadataItem('CUTLINE',poly)
            if self.name:
                dst_ds.SetMetadataItem('DESCRIPTION',self.name.encode('utf-8'))

            dst_ds = None # close dataset
#            re_sub_file(dst_file, [
#                    ('^.*<GeoTransform>.*\n',''),
#                    ('^.*<SRS>.*\n','')
#                    ])
        finally:
            self.raster_ds = None
            os.chdir(start_dir)

        if options.get_cutline: # print cutline then return
            print poly
            return
        if gmt_data and options.cut_file: # create shapefile with a cut polygon
            with open(base+'.gmt','w+') as f:
                f.write(gmt_data)

        return dst_file
示例#21
0
def create_gcp_list(latitude, longitude, rescaling_coef=1.0):

    n_gcp = 150  # Maximum allow GCPs
    percentage_gcp_per_line = 0.2

    latitude_ds = gdal.OpenShared(str(latitude))
    longitude_ds = gdal.OpenShared(str(longitude))
    lat = (latitude_ds.GetRasterBand(1)).ReadAsArray().astype(np.float32)
    lon = (longitude_ds.GetRasterBand(1)).ReadAsArray().astype(np.float32)
    gcp_list_o = []

    pas_pixel = np.int(latitude_ds.RasterXSize * percentage_gcp_per_line) + 1
    pas_line = np.int((latitude_ds.RasterYSize * latitude_ds.RasterXSize) /
                      (n_gcp * pas_pixel)) + 1

    print latitude_ds.RasterXSize / pas_pixel, ' ', latitude_ds.RasterYSize / pas_line
    k = 0
    for line in range(0, latitude_ds.RasterYSize - 1, pas_line):
        for px in range(0, latitude_ds.RasterXSize - 1, pas_pixel):
            gcp = gdal.GCP(
                np.multiply(np.double(lon[line][px]), rescaling_coef),
                np.multiply(np.double(lat[line][px]), rescaling_coef), 0, (px),
                (line))
            gcp_list_o.append(gcp)
            k = k + 1

    latitude_ds = None
    longitude_ds = None

    return gcp_list_o  #Gdal osgeo gcp object
示例#22
0
def test_tps_1():

    drv = gdal.GetDriverByName('MEM')
    ds = drv.Create('foo', 2, 2)
    gcp_list = [
        gdal.GCP(0, 0, 0, 0, 0),
        gdal.GCP(0, 50, 0, 0, 50),
        gdal.GCP(50, 0, 0, 50, 0),
        gdal.GCP(50, 50, 0, 50, 50),
        gdal.GCP(0 * 25, 0 * 25, 0, 25, 25),
    ]
    ds.SetGCPs(gcp_list, osr.GetUserInputAsWKT('WGS84'))
    utm_wkt = osr.GetUserInputAsWKT('+proj=utm +zone=11 +datum=WGS84')

    with gdaltest.error_handler():
        transformer = gdal.Transformer(
            ds, None, ['DST_SRS=' + utm_wkt, 'METHOD=GCP_TPS'])
    assert transformer is None
示例#23
0
def SetGCPsToGeoTransform(cornerPointUL, cornerPointUR, cornerPointLR,
                          cornerPointLL, frameCenterLon, frameCenterLat):
    ''' Make Geotranform from pixel to lon lat coordinates '''
    gcps = []

    global gcornerPointUL
    gcornerPointUL = cornerPointUL
    global gcornerPointUR
    gcornerPointUR = cornerPointUR
    global gcornerPointLR
    gcornerPointLR = cornerPointLR
    global gcornerPointLL
    gcornerPointLL = cornerPointLL
    global gframeCenterLat
    gframeCenterLat = frameCenterLat
    global gframeCenterLon
    gframeCenterLon = frameCenterLon

    Height = 0
    gcp = gdal.GCP(cornerPointUL[1], cornerPointUL[0], Height, 0, 0,
                   "Corner Upper Left", "1")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointUR[1], cornerPointUR[0], Height, xSize, 0,
                   "Corner Upper Right", "2")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLR[1], cornerPointLR[0], Height, xSize, ySize,
                   "Corner Lower Right", "3")
    gcps.append(gcp)
    gcp = gdal.GCP(cornerPointLL[1], cornerPointLL[0], Height, 0, ySize,
                   "Corner Lower Left", "4")
    gcps.append(gcp)
    gcp = gdal.GCP(frameCenterLon, frameCenterLat, Height, xSize / 2,
                   ySize / 2, "Center", "5")
    gcps.append(gcp)

    global geotransform
    geotransform = gdal.GCPsToGeoTransform(gcps)

    if geotransform is None:
        qgsu.showUserAndLogMessage(QCoreApplication.translate(
            "QgsFmvUtils", 'Unable to extract a geotransform.'),
                                   onlyLog=True)

    return
示例#24
0
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
示例#25
0
文件: mem.py 项目: kongdd/gdal
def test_mem_1():

    #######################################################
    # Setup dataset
    drv = gdal.GetDriverByName('MEM')
    gdaltest.mem_ds = drv.Create('mem_1.mem', 50, 3)
    ds = gdaltest.mem_ds

    assert ds.GetProjection() == '', 'projection wrong'

    assert ds.GetGeoTransform(can_return_null=True) is None, 'geotransform wrong'

    raw_data = b''.join(struct.pack('f', v) for v in range(150))
    ds.WriteRaster(0, 0, 50, 3, raw_data,
                   buf_type=gdal.GDT_Float32,
                   band_list=[1])

    wkt = gdaltest.user_srs_to_wkt('EPSG:26711')
    ds.SetProjection(wkt)

    gt = (440720, 5, 0, 3751320, 0, -5)
    ds.SetGeoTransform(gt)

    band = ds.GetRasterBand(1)
    band.SetNoDataValue(-1.0)

    # Set GCPs()
    wkt_gcp = gdaltest.user_srs_to_wkt('EPSG:4326')
    gcps = [gdal.GCP(0, 1, 2, 3, 4)]
    ds.SetGCPs([], "")
    ds.SetGCPs(gcps, wkt_gcp)
    ds.SetGCPs([], "")
    ds.SetGCPs(gcps, wkt_gcp)
    ds.SetGCPs(gcps, wkt_gcp)

    #######################################################
    # Verify dataset.

    assert band.GetNoDataValue() == -1.0, 'no data is wrong'

    assert ds.GetProjection() == wkt, 'projection wrong'

    assert ds.GetGeoTransform() == gt, 'geotransform wrong'

    assert band.Checksum() == 1531, 'checksum wrong'

    assert ds.GetGCPCount() == 1, 'GetGCPCount wrong'

    assert len(ds.GetGCPs()) == 1, 'GetGCPs wrong'

    assert ds.GetGCPProjection() == wkt_gcp, 'GetGCPProjection wrong'

    assert band.DeleteNoDataValue() == 0, 'wrong return code'
    assert band.GetNoDataValue() is None, 'got nodata value whereas none was expected'

    gdaltest.mem_ds = None
示例#26
0
def _list2gcps(src_list):
    gcp_list = []
    for src_tuple in src_list:
        gcp = gdal.GCP()
        gcp.GCPPixel = src_tuple[0]
        gcp.GCPLine = src_tuple[1]
        gcp.GCPX = src_tuple[2]
        gcp.GCPY = src_tuple[3]
        gcp_list.append(gcp)
    return gcp_list
示例#27
0
def georeference_image(image_input_filepath, image_output_filepath, image_width, image_height, map_bottom, map_top, map_left, map_right):
    dataset = gdal.Open(str(image_input_filepath), gdal.GA_Update)
    sr = osr.SpatialReference()
    sr.ImportFromEPSG(4326)
    # Enter the GCPs
    #   Format: [map x-coordinate(longitude)], [map y-coordinate (latitude)], [elevation],
    #   [image column index(x)], [image row index (y)]
    gcps = [
        gdal.GCP(map_left, map_bottom, 0, 0, image_height),
        gdal.GCP(map_right, map_bottom, 0, image_width, image_height),
        gdal.GCP(map_right, map_top, 0, image_width, 0),
        gdal.GCP(map_left, map_top, 0, 0, 0)]

    # Apply the GCPs to the open output file:
    dataset.SetGCPs(gcps, sr.ExportToWkt())
    gdal.Warp(str(image_output_filepath), dataset, dstSRS='EPSG:4326', format='gtiff')

    # Close the output file in order to be able to work with it in other programs:
    dataset = None
示例#28
0
def test_overviewds_3():

    src_ds = gdal.Open('data/byte.tif')
    ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/byte.tif', src_ds)
    ds.SetGeoTransform([0, 1, 0, 0, 0, 1])  # cancel geotransform
    gcp1 = gdal.GCP()
    gcp1.GCPPixel = 0
    gcp1.GCPLine = 0
    gcp1.GCPX = 440720.000
    gcp1.GCPY = 3751320.000
    gcp2 = gdal.GCP()
    gcp2.GCPPixel = 0
    gcp2.GCPLine = 20
    gcp2.GCPX = 440720.000
    gcp2.GCPY = 3750120.000
    gcp3 = gdal.GCP()
    gcp3.GCPPixel = 20
    gcp3.GCPLine = 0
    gcp3.GCPX = 441920.000
    gcp3.GCPY = 3751320.000
    src_gcps = (gcp1, gcp2, gcp3)
    ds.SetGCPs(src_gcps, src_ds.GetProjectionRef())

    tr = gdal.Transformer(ds, None, ['METHOD=GCP_POLYNOMIAL'])
    (_, ref_pnt) = tr.TransformPoint(0, 20, 10)

    ds.BuildOverviews('NEAR', overviewlist=[2, 4])
    ds = None

    ds = gdal.OpenEx('tmp/byte.tif', open_options=['OVERVIEW_LEVEL=0'])
    gcps = ds.GetGCPs()
    for i in range(3):
        assert (gcps[i].GCPPixel == src_gcps[i].GCPPixel / 2 and gcps[i].GCPLine == src_gcps[i].GCPLine / 2 and \
           gcps[i].GCPX == src_gcps[i].GCPX and gcps[i].GCPY == src_gcps[i].GCPY)

    # Really check that the transformer works
    tr = gdal.Transformer(ds, None, ['METHOD=GCP_POLYNOMIAL'])
    (_, pnt) = tr.TransformPoint(0, 20 / 2.0, 10 / 2.0)

    for i in range(3):
        assert abs(ref_pnt[i] - pnt[i]) <= 1e-5
    ds = None
示例#29
0
def tps_1():

    drv = gdal.GetDriverByName('MEM')
    ds = drv.Create('foo', 2, 2)
    gcp_list = [
        gdal.GCP(0, 0, 0, 0, 0),
        gdal.GCP(0, 50, 0, 0, 50),
        gdal.GCP(50, 0, 0, 50, 0),
        gdal.GCP(50, 50, 0, 50, 50),
        gdal.GCP(0 * 25, 0 * 25, 0, 25, 25),
    ]
    ds.SetGCPs(gcp_list, osr.GetUserInputAsWKT('WGS84'))
    utm_wkt = osr.GetUserInputAsWKT('+proj=utm +zone=11 +datum=WGS84')

    transformer = gdal.Transformer(ds, None,
                                   ['DST_SRS=' + utm_wkt, 'METHOD=GCP_TPS'])
    if transformer is None or gdal.GetLastErrorType() == 0:
        return 'fail'

    return 'success'
示例#30
0
def transform_gcps(gcps, imageHeight, dst):
    src = osr.SpatialReference()
    src.ImportFromEPSG(4326)
    tr = osr.CoordinateTransformation(src, dst)
    ret = []
    for gcp in gcps:
        x, y, z = tr.TransformPoint(gcp.ground.get_x(), gcp.ground.get_y(),
                                    0.0)
        ret.append(
            gdal.GCP(x, y, z, gcp.image.get_x(),
                     imageHeight - gcp.image.get_y()))
    return ret