GDAL用shapefile绘制tif

时间:2018-10-16 20:15:49

标签: python gdal

基本上,我要做的是创建一个新图像,该图像为白色,不存在任何特征,黑色为存在一个特征。

我不知道允许进行此类转换的任何api。

<=编辑 我正在尝试另一种解决方案,获取每个功能的像素坐标,然后创建图像

这是代码

def retrieve_pixel_value(geo_coord, data_source):
    from affine import Affine
    x, y = geo_coord[0], geo_coord[1]
    forward_transform =  \
    Affine.from_gdal(*data_source.GetGeoTransform())
    reverse_transform = ~forward_transform
    px, py = reverse_transform * (x, y)
    px, py = int(px + 0.5), int(py + 0.5)
    pixel_coord = px, py
    return (pixel_coord)

但是它似乎不起作用 来源:https://gis.stackexchange.com/questions/221292/retrieve-pixel-value-with-geographic-coordinate-as-input-with-gdal

<=编辑2 创建了此功能

def createFeatureTable(shp_filename , src_filename):
    from osgeo import gdal,ogr
    import osgeo.ogr
    osgeo.ogr.UseExceptions()
    import struct
    from PIL import Image

    ds=osgeo.ogr.Open(shp_filename)
    lyr=ds.GetLayer()

    driver = gdal.GetDriverByName('GTiff')
    dataset = gdal.Open(src_filename)
    band = dataset.GetRasterBand(1)

    cols = dataset.RasterXSize
    rows = dataset.RasterYSize

    transform = dataset.GetGeoTransform()

    xOrigin = transform[0]
    yOrigin = transform[3]
    pixelWidth = transform[1]
    pixelHeight = -transform[5]

    data = band.ReadAsArray(0, 0, cols, rows)
    pixel_coords = []
    print("Checkpoint 1")
    for feat in lyr:
        geom = feat.GetGeometryRef()
        ring = geom.GetGeometryRef(0)
        points = ring.GetPointCount()

        for p in range(0,points):
            x,y,z = ring.GetPoint(p)
            cord = x,y
            res = retrieve_pixel_value(cord,dataset)
            pixel_coords.append(res)
    import numpy as np
    img = np.zeros([7532,5462,3],dtype=np.uint8)
    img.fill(255) # or img[:] = 255
    print("Checkpoint 3")
    for coordinate in pixel_coords:
        img[coordinate[0],coordinate[1],0] = 0
        img[coordinate[0],coordinate[1],1] = 0
        img[coordinate[0],coordinate[1],2] = 0
    print("Checkpoint 4")

    image = Image.fromarray(img, 'RGB')
    image.save('testOut.jpg')

示例输出:

EO1

如您所见,要素未填充且线条不够完美

0 个答案:

没有答案