Ejemplo n.º 1
0
def main(shapefile_path, raster_path):
    # Load the source data as a gdalnumeric array
    srcArray = gdalnumeric.LoadFile(raster_path)

    # Also load as a gdal image to get geotransform
    # (world file) info
    pdb.set_trace()

    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()

    # Create an OGR layer from a boundary shapefile
    shapef = ogr.Open(shapefile_path)
    lyr = shapef.GetLayer(
        os.path.split(os.path.splitext(shapefile_path)[0])[1])

    poly = lyr.GetNextFeature()

    # Convert the layer extent to image pixel coordinates
    minX, maxX, minY, maxY = lyr.GetExtent()
    ulX, ulY = world2Pixel(geoTrans, minX, maxY)
    lrX, lrY = world2Pixel(geoTrans, maxX, minY)

    # Calculate the pixel size of the new image
    pxWidth = int(lrX - ulX)
    pxHeight = int(lrY - ulY)

    clip = srcArray[:, ulY:ulY + 1000, ulX:ulX + 1000]

    # Save as an 8-bit jpeg for an easy, quick preview
    clip = clip.astype(gdalnumeric.uint8)
    gdalnumeric.SaveArray(clip, "beijing3.jpg", format="JPEG")
Ejemplo n.º 2
0
def merge_floods(dirPaese):

    os.chdir(dirPaese)
    iso_paese = dirPaese.split("\\")[-1]
    print iso_paese
    stringa_ricerca = "*.tif"
    lista_floods_rcl = glob.glob(stringa_ricerca)
    print lista_floods_rcl
    for floodo in lista_floods_rcl:
        rp = floodo.split("_")[1].split(".")[0]
        if rp == '25':
            im_rp_25 = floodo
        elif rp == '50':
            im_rp_50 = floodo
        elif rp == '100':
            im_rp_100 = floodo
        elif rp == '200':
            im_rp_200 = floodo
        elif rp == '500':
            im_rp_500 = floodo
        elif rp == '1000':
            im_rp_1000 = floodo

    ar25 = gdalnumeric.LoadFile(im_rp_25).astype(np.int16)
    ar50 = gdalnumeric.LoadFile(im_rp_50).astype(np.int16)
    ar100 = gdalnumeric.LoadFile(im_rp_100).astype(np.int16)
    ar200 = gdalnumeric.LoadFile(im_rp_200).astype(np.int16)
    ar500 = gdalnumeric.LoadFile(im_rp_500).astype(np.int16)
    ar1000 = gdalnumeric.LoadFile(im_rp_1000).astype(np.int16)
    somma = ar25 + ar50 + ar100 + ar200 + ar500 + ar1000
    gdalnumeric.SaveArray(somma,
                          dirPaese + "\\" + iso_paese + "_all_rp.tif",
                          format="GTiff",
                          prototype=im_rp_1000)
Ejemplo n.º 3
0
def main(shapefile_path, raster_path, fileName):
    # 读取栅格影像路径
    srcArray = gdalnumeric.LoadFile(raster_path)
    # 读取栅格据
    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()
    # 读取矢量图形数据路径
    shapef = ogr.Open(shapefile_path)
    lyr = shapef.GetLayer(
        os.path.split(os.path.splitext(shapefile_path)[0])[1])
    poly = lyr.GetNextFeature()
    # 矢量图形坐标换算
    minX, maxX, minY, maxY = lyr.GetExtent()
    ulX, ulY = world2Pixel(geoTrans, minX, maxY)
    lrX, lrY = world2Pixel(geoTrans, maxX, minY)
    # 计算新生成图像大小
    pxWidth = int(lrX - ulX)
    pxHeight = int(lrY - ulY)
    clip = srcArray[:, ulY:lrY, ulX:lrX]
    xoffset = ulX
    yoffset = ulY
    print("Xoffset, Yoffset = ( %f, %f )" % (xoffset, yoffset))
    # 创建geomatrix
    geoTrans = list(geoTrans)
    geoTrans[0] = minX
    geoTrans[3] = maxY
    # 创建一张黑白遮罩图像,将矢量点集映射到像素上
    points = []
    pixels = []
    geom = poly.GetGeometryRef()
    pts = geom.GetGeometryRef(0)
    for p in range(pts.GetPointCount()):
        points.append((pts.GetX(p), pts.GetY(p)))
    for p in points:
        pixels.append(world2Pixel(geoTrans, p[0], p[1]))
    rasterPoly = Image.new("L", (pxWidth, pxHeight), 1)
    rasterize = ImageDraw.Draw(rasterPoly)
    rasterize.polygon(pixels, 0)
    mask = imageToArray(rasterPoly)
    # 裁剪遮罩
    clip = gdalnumeric.choose(mask, (clip, 0)).astype(gdalnumeric.int16)
    clip = clip.astype(gdalnumeric.int16)
    #加载GTiff驱动,存储结果为tiff图像
    gtiffDriver = gdal.GetDriverByName('GTiff')
    if gtiffDriver is None:
        raise ValueError("Can't load GeoTiff Driver")
    print(type(clip))
    gdalnumeric.SaveArray(clip, fileName, format="GTiff")
    print("裁剪完毕")
    gdal.ErrorReset()
Ejemplo n.º 4
0
def merge_floods(paese):
    os.chdir("C:/data/tools/sparc/input_data/flood/masks/")
    stringa_ricerca = "%s*.tif" % paese
    lista_floods_rcl = glob.glob(stringa_ricerca)
    print lista_floods_rcl
    im_rp_25 = lista_floods_rcl[3]
    im_rp_50 = lista_floods_rcl[5]
    im_rp_100 = lista_floods_rcl[1]
    im_rp_200 = lista_floods_rcl[2]
    im_rp_500 = lista_floods_rcl[4]
    im_rp_1000 = lista_floods_rcl[0]
    ar25 = gdalnumeric.LoadFile(im_rp_25).astype(np.int16)
    ar50 = gdalnumeric.LoadFile(im_rp_50).astype(np.int16)
    ar100 = gdalnumeric.LoadFile(im_rp_100).astype(np.int16)
    ar200 = gdalnumeric.LoadFile(im_rp_200).astype(np.int16)
    ar500 = gdalnumeric.LoadFile(im_rp_500).astype(np.int16)
    ar1000 = gdalnumeric.LoadFile(im_rp_1000).astype(np.int16)
    somma = ar25 + ar50 + ar100 + ar200 + ar500 + ar1000
    gdalnumeric.SaveArray(somma,
                          "C:/data/tools/sparc/input_data/flood/merged/" +
                          paese + "_all_rp.tif",
                          format="GTiff",
                          prototype=im_rp_1000)
Ejemplo n.º 5
0
def main():
    RasterFilePath = sys.argv[1]
    #Raster input as MSI
    MSIImage = gdal.Open(RasterFilePath)

    infotext = os.system('gdalinfo' + ' ' + RasterFilePath)
    print infotext
    XSize = MSIImage.RasterXSize
    YSize = MSIImage.RasterYSize
    MSIGeoTrans = MSIImage.GetGeoTransform()
    print MSIGeoTrans
    pixelSizeX = MSIGeoTrans[1]
    pixelSizeY = MSIGeoTrans[5]
    RasterBand_Count = MSIImage.RasterCount
    print XSize, YSize, RasterBand_Count, pixelSizeX, pixelSizeY
    for i in range(RasterBand_Count):
        bandarray = np.array(MSIImage.GetRasterBand(i + 1).ReadAsArray())
        print bandarray.shape
        #print bandarray
        #Shapefile for landusage
    ShapeFilePath = sys.argv[2]
    SHPFILE_LandUsage = ogr.Open(ShapeFilePath)
    layer = SHPFILE_LandUsage.GetLayer(0)
    minX, maxX, minY, maxY = layer.GetExtent()
    raster_minX = -81.690277778  #Hardcoded with following 3 lines
    raster_minY = 30.298888889
    raster_maxX = -81.456388889
    raster_maxY = 30.400555556
    if (minX < raster_minX):
        X_translate = abs(minX - raster_minX)
    if (minY < raster_minY):
        Y_translate = abs(minY - raster_minY)
    xDist = 0.000025379  #geoMatrix[1] #Hardcoded 2 lines
    yDist = 0.000014183  #geoMatrix[5]
    X_translate_pixels = int(X_translate / xDist)
    Y_translate_pixels = int(Y_translate / yDist)
    print minX, raster_minX, minY, raster_minY, maxX, raster_maxX, maxY, raster_maxY
    ulX, ulY = world2pixelraster(MSIGeoTrans, raster_minX, raster_maxY)
    lrX, lrY = world2pixelraster(MSIGeoTrans, raster_maxX, raster_minY)
    s_ulX, s_ulY = world2pixelraster(MSIGeoTrans, minX, maxY)
    s_lrX, s_lrY = world2pixelraster(MSIGeoTrans, maxX, minY)

    #ulX=ulX+X_translate_pixels
    #ulY=ulY+Y_translate_pixels
    #lrX=lrX+X_translate_pixels
    #lrY=lrY+Y_translate_pixels

    print('Pixel Extent', ulX, lrX, ulY, lrY)
    pxWidth = int(lrX - ulX)

    pxHeight = int(lrY - ulY)
    srcArray = np.zeros((8, YSize, XSize), dtype=float)
    #srcArray=gdalnumeric.LoadFile('/projects/bialvm/Jhimli/MSI_JacksonVille_WV2/05SEP16WV021200016SEP05162552-M1BS-500881026010_01_P006_________GA_E0AAAAAAIAAG0.NTF')#(np.zeros((8,YSize,XSize),dtype=float)
    for i in range(RasterBand_Count):
        bandarray = np.array(
            MSIImage.GetRasterBand(i + 1).ReadAsArray().astype(np.float32))
        srcArray[i, :, :] = bandarray
    cliparray = srcArray[:, ulY:lrY, ulX:lrX]
    newclip = np.zeros((pxHeight, pxWidth, 8), dtype=float)
    for i in range(0, 8):
        newclip[:, :, i] = cliparray[i, :, :]
    OutputFolderPath = sys.argv[3]
    cv2.imwrite(os.path.join(OutputFolderPath + 'clipraster.png'),
                newclip[:, :, 1])
    #pdb.set_trace()
    xoffset = s_ulX
    yoffset = s_ulY
    print(lrY, s_lrY)
    scale_Y = float(lrY) / float(s_lrY)
    scale_X = float(ulX) / float(s_ulX)
    print('YScale:', scale_Y)
    print('XScale:', scale_X)
    print('Xoffset', xoffset, 'Yoffset', yoffset)
    geoTrans = list(MSIGeoTrans)
    geoTrans[0] = minX
    geoTrans[3] = maxY

    print geoTrans[0], geoTrans[3]
    #ds=gdal.GetDriverByName('gtiff').Create('/projects/bialvm/Jhimli/wood_raster.tif',XSize,YSize,1)
    #ds.SetGeoTransform([ulx,1,0,uly,0,-1])
    #print layer.GetSpatialRef().ExportToWkt()
    #ds.SetProjection(layer.GetSpatialRef().ExportToWkt())

    #Extracting geometry by material type from shape file landuasages
    multipolygon = ogr.Geometry(ogr.wkbMultiPolygon)
    layer.SetAttributeFilter("type='stadium'")
    #print layer
    #new_band=ds.GetRasterBand(1)
    #new_band.SetNoDataValue(0)
    #gdal.RasterizeLayer(ds,[1],layer,None, None, [1], ['ALL_TOUCHED=TRUE'])
    allpoly = []
    for feature in layer:
        type_name = feature.GetField("type")
        geometry = feature.GetGeometryRef()
        rcnt = 0
        for ring in geometry:
            rcnt += 1
            points = ring.GetPointCount()
            pcnt = 0
            poly_coords = []
            poly_pixels = []
            for p in xrange(points):
                pcnt += 1
                lon, lat, z = ring.GetPoint(p)
                #print lon,lat,z
                poly_coords.append([lon, lat])
            for p in poly_coords:
                px_X, px_Y = world2pixelshape(geoTrans, p[0], p[1])
                poly_pixels.append((px_X - xoffset, int(px_Y * scale_Y)))

        allpoly.append(poly_pixels)
    print allpoly
    rasterPoly = Image.new("L", (pxWidth, pxHeight), 1)
    rasterize = ImageDraw.Draw(rasterPoly)
    for i in range(len(allpoly)):
        print allpoly[i]
        rasterize.polygon(allpoly[i], 0)
    print(pxWidth, pxHeight)
    mask = imageToArray(rasterPoly)

    mask = mask.astype(gdalnumeric.uint8)
    maskFileName = os.path.join(OutputFolderPath + 'mask.jpg')
    gdalnumeric.SaveArray(mask * 255, maskFileName, format="JPEG")

    for i in range(8):
        cliparray[i, :, :] = cliparray[i, :, :]
    # Save as an 8-bit jpeg for an easy, quick preview
    clipImage = np.zeros((pxHeight, pxWidth, 3), dtype=np.uint8)
    for kk in range(0, 3):
        clipImage[:, :, kk] = cliparray[kk, :, :].astype(gdalnumeric.uint8)
    #mask=mask.astype(gdalnumeric.uint8)
    new_mask = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
    new_mask[:, :, 0] = 255 * mask
    new_mask[:, :, 1] = mask
    new_mask[:, :, 2] = mask

    #pdb.set_trace()
    result_img = cv2.addWeighted(new_mask, 0.5, clipImage, 0.5, 0)
    ShapeMaskOnRasterFile = os.path.join(OutputFolderPath + 'OUTPUT.png')
    cv2.imwrite(ShapeMaskOnRasterFile, result_img)

    #gdalnumeric.SaveArray(clipImage, "/projects/bialvm/Jhimli/OUTPUT.jpg", format="JPEG")
    '''
# Numpy/gdalnumeric - Read an image, extract a band, save a new image

# https://github.com/GeospatialPython/Learning/raw/master/SatImage.zip

from osgeo import gdalnumeric
srcArray = gdalnumeric.LoadFile("SatImage.tif")
band1 = srcArray[0]
gdalnumeric.SaveArray(band1, "band1.jpg", format="JPEG")
def clip(tiff_gt,
         tiff_arr,
         geom,
         no_data=-10000,
         clip_save_name='',
         is_clip_saved_in_png=True):
    '''
    Clip GeoTiff from `tiff_path` with ShapeFile from `shape_path`.

    Parameters
    ----------
    tiff : osgeo.gdal.Dataset
        path to `.tif` file
    shape_path : osgeo.ogr.DataSource
        path to `.shp` file
        :param clip_save_name: the name of saving clip. Empty string '' to not save. i.e. 'clipped-img'
        :param is_clip_saved_in_png: True to save in PNG (8-bit), and False to save in GeoTiff format (Float32)
    '''
    gdal.UseExceptions()

    # tiff_arr_shape = tiff_arr.shape
    # tiff_pxl_ext = eu.tup_to_dic((
    #     0, tiff_arr_shape[0],
    #     0, tiff_arr_shape[1],
    # ))
    geom_pts = get_pts_in_geom(geom)

    # Get the geo-extent of the geo polygon
    geom_ext = make_geom_ext(geom_pts)

    # Get the geo extent in pixel coordinates
    geom_pxl_ext = {
        k: int(v)
        for k, v in eu.apply_gt(gdal.InvGeoTransform(tiff_gt),
                                geom_ext).items()
    }

    geom_gt = make_geom_gt(tiff_gt, geom_ext)
    geom_inv_gt = gdal.InvGeoTransform(geom_gt)

    tiff_shape = tiff_arr.shape

    if geom_pxl_ext['min_y'] < 0:
        geom_pxl_ext['min_y'] = 0
    if geom_pxl_ext['min_x'] < 0:
        geom_pxl_ext['min_x'] = 0
    if geom_pxl_ext['max_y'] < 0:
        geom_pxl_ext['max_y'] = 0
    if geom_pxl_ext['max_x'] < 0:
        geom_pxl_ext['max_x'] = 0

    # Extract data from dsm (tiff_arr) to the extent (clipped_arr)
    if len(tiff_shape) == 3:
        bound_tiff_y = tiff_shape[1] - 1
        bound_tiff_x = tiff_shape[2] - 1
        if geom_pxl_ext['max_y'] > bound_tiff_y:
            geom_pxl_ext['max_y'] = bound_tiff_y
        if geom_pxl_ext['max_x'] > bound_tiff_x:
            geom_pxl_ext['max_x'] = bound_tiff_x

        clipped_arr = tiff_arr[:,
                               geom_pxl_ext['min_y']:geom_pxl_ext['max_y'] + 1,
                               geom_pxl_ext['min_x']:geom_pxl_ext['max_x'] +
                               1, ]
    else:
        bound_tiff_y = tiff_shape[0] - 1
        bound_tiff_x = tiff_shape[1] - 1
        if geom_pxl_ext['max_y'] > bound_tiff_y:
            geom_pxl_ext['max_y'] = bound_tiff_y
        if geom_pxl_ext['max_x'] > bound_tiff_x:
            geom_pxl_ext['max_x'] = bound_tiff_x

        clipped_arr = tiff_arr[np.newaxis,
                               geom_pxl_ext['min_y']:geom_pxl_ext['max_y'] + 1,
                               geom_pxl_ext['min_x']:geom_pxl_ext['max_x'] +
                               1, ]

    # Convert the geo-polygon-points from geo-referenced to coordinates in Pixel (based on the extent)
    pxls = [
        tuple(map(int, gdal.ApplyGeoTransform(geom_inv_gt, x, y)))
        for (x, y) in geom_pts
    ]

    # FIXME:
    # This code make incorrect volume.
    # For example, when you have a triangle with
    # one point going outside to the map,
    # the point will be filtered and result volume will be 0.
    ext_bound_x = geom_pxl_ext['max_x'] - geom_pxl_ext['min_x']
    ext_bound_y = geom_pxl_ext['max_y'] - geom_pxl_ext['min_y']
    clipped_pxls = [(x, y) for (x, y) in pxls
                    if 0 <= x <= ext_bound_x and 0 <= y <= ext_bound_y]

    if len(clipped_pxls) < 2:
        return np.array([]), []

    raster_size = (ext_bound_x + 1, ext_bound_y + 1)
    raster_poly = Image.new('L', raster_size, color=0x000001)
    ImageDraw.Draw(raster_poly).polygon(clipped_pxls, fill=0x000000)

    # TODO: Add error handlings for ValueError
    mask = np.fromstring(raster_poly.tobytes(), dtype=np.int8) \
        .reshape(raster_poly.im.size[1], raster_poly.im.size[0])

    clipped_arr = np.choose(mask, (clipped_arr, no_data))
    boundary_pts = [clipped_arr[0, y, x] for (x, y) in clipped_pxls]

    ######### TESTING BEGIN
    # Save the clipped image to a PNG file
    if len(clip_save_name) > 0:
        if is_clip_saved_in_png:
            clippedData = clipped_arr.astype(np.int8)
            gdalnumeric.SaveArray(clippedData,
                                  clip_save_name + '.png',
                                  format="PNG")
        else:
            clippedData = clipped_arr.astype(np.float32)
            gdalnumeric.SaveArray(clippedData,
                                  clip_save_name + '.tif',
                                  format="GTiff")
    ######### TESTING END

    return clipped_arr, boundary_pts
'''

from osgeo import gdal, gdalnumeric
import numpy as np

im1 = './data/remote_sensing/before.tif'
im2 = './data/remote_sensing/after.tif'
ar1 = gdalnumeric.LoadFile(im1).astype(np.int8)
ar2 = gdalnumeric.LoadFile(im2)[1].astype(np.int8)
diff = ar2 - ar1

classes = np.histogram(diff, bins=5)[1]
lut = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 255, 0], [255, 0, 0]]

start = 1
rgb = np.zeros((
    3,
    diff.shape[0],
    diff.shape[1],
), np.int8)
for i in range(len(classes)):
    mask = np.logical_and(start <= diff, diff <= classes[i])
    for j in range(len(lut[i])):
        rgb[j] = np.choose(mask, (rgb[j], lut[i][j]))
    start = classes[i] + 1

gdalnumeric.SaveArray(rgb,
                      './data/remote_sensing/change.tif',
                      format='GTiff',
                      prototype=im2)
def gdalNum():
    srcArray = gdalnumeric.LoadFile("SatImage.tif")
    band1 = srcArray[0]
    gdalnumeric.SaveArray(band1, "band1.jpg", format="JPEG")
Ejemplo n.º 10
0
# 地图上的点到用在空白的8位黑白掩模图像上绘制边界的像素
points = []
pixels = []
geom = poly.GetGeometryRef()
pts = geom.GetGeometryRef(0)
for p in range(pts.GetPointCount()):
    points.append((pts.GetX(p), pts.GetY(p)))
for p in points:
    pixels.append(world2Pixel(geoTrans, p[0], p[1]))
rasterPoly = Image.new("L", (pxWidth, pxHeight), 1)
rasterize = ImageDraw.Draw(rasterPoly)
rasterize.polygon(pixels, 0)
mask = imageToArray(rasterPoly)

# 用掩模裁剪图像
clip = gdalnumeric.choose(mask, (clip, 0)).astype(gdalnumeric.uint8)

# 这个图像有3个波段,因此我们得拉伸每一个波段使得他们有更好的可视化效果
for i in range(3):
    clip[i, :, :] = stretch(clip[i, :, :])

# 将ndvi另存为tiff
gdalnumeric.SaveArray(clip,
                      "%s.tiff" % output,
                      format="GTiff",
                      prototype=raster)

# 将ndvi保存为8位的jpeg,以便于快速预览
clip = clip.astype(gdalnumeric.uint8)
gdalnumeric.SaveArray(clip, "%s.jpg" % output, format="JPEG")
Ejemplo n.º 11
0
def clip_raster1(shapefile_path, raster_path):
    '''
    This function will convert the rasterized clipper shapefile
    to a mask for use within GDAL.

    This comes (with slight modification) from:

    https://pcjericks.github.io/py-gdalogr-cookbook/raster_layers.html#clip-a-geotiff-with-shapefile

    which is an updated version of:
    
    http://geospatialpython.com/2011/02/clip-raster-using-shapefile.html
    '''
    def imageToArray(i):
        """
        Converts a Python Imaging Library array to a
        gdalnumeric image.
        """
        a = gdalnumeric.fromstring(i.tostring(), 'b')
        a.shape = i.im.size[1], i.im.size[0]
        return a

    def arrayToImage(a):
        """
        Converts a gdalnumeric array to a
        Python Imaging Library Image.
        """
        i = Image.fromstring('L', (a.shape[1], a.shape[0]),
                             (a.astype('b')).tostring())
        return i

    def world2Pixel(geoMatrix, x, y):
        """
        Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
        the pixel location of a geospatial coordinate
        """
        ulX = geoMatrix[0]
        ulY = geoMatrix[3]
        xDist = geoMatrix[1]
        yDist = geoMatrix[5]
        rtnX = geoMatrix[2]
        rtnY = geoMatrix[4]
        pixel = int((x - ulX) / xDist)
        line = int((ulY - y) / xDist)
        return (pixel, line)

    #  EDIT: this is basically an overloaded
    #  version of the gdal_array.OpenArray passing in xoff, yoff explicitly
    #  so we can pass these params off to CopyDatasetInfo
    #
    def OpenArray(array, prototype_ds=None, xoff=0, yoff=0):
        ds = gdal.Open(gdalnumeric.GetArrayFilename(array))

        if ds is not None and prototype_ds is not None:
            if type(prototype_ds).__name__ == 'str':
                prototype_ds = gdal.Open(prototype_ds)
            if prototype_ds is not None:
                gdalnumeric.CopyDatasetInfo(prototype_ds,
                                            ds,
                                            xoff=xoff,
                                            yoff=yoff)
        return ds

    def histogram(a, bins=range(0, 256)):
        """
        Histogram function for multi-dimensional array.
        a = array
        bins = range of numbers to match
        """
        fa = a.flat
        n = gdalnumeric.searchsorted(gdalnumeric.sort(fa), bins)
        n = gdalnumeric.concatenate([n, [len(fa)]])
        hist = n[1:] - n[:-1]
        return hist

    def stretch(a):
        """
        Performs a histogram stretch on a gdalnumeric array image.
        """
        hist = histogram(a)
        im = arrayToImage(a)
        lut = []
        for b in range(0, len(hist), 256):
            # step size
            step = reduce(operator.add, hist[b:b + 256]) / 255
            # create equalization lookup table
            n = 0
            for i in range(256):
                lut.append(n / step)
                n = n + hist[i + b]
        im = im.point(lut)
        return imageToArray(im)

    # Load the source data as a gdalnumeric array
    srcArray = gdalnumeric.LoadFile(raster_path)

    # Also load as a gdal image to get geotransform
    # (world file) info
    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()

    # Create an OGR layer from a boundary shapefile
    shapef = ogr.Open(shapefile_path)
    lyr = shapef.GetLayer(
        os.path.split(os.path.splitext(shapefile_path)[0])[1])
    poly = lyr.GetNextFeature()

    # Convert the layer extent to image pixel coordinates
    minX, maxX, minY, maxY = lyr.GetExtent()
    ulX, ulY = world2Pixel(geoTrans, minX, maxY)
    lrX, lrY = world2Pixel(geoTrans, maxX, minY)

    # Calculate the pixel size of the new image
    pxWidth = int(lrX - ulX)
    pxHeight = int(lrY - ulY)

    clip = srcArray[:, ulY:lrY, ulX:lrX]

    #
    # EDIT: create pixel offset to pass to new image Projection info
    #
    xoffset = ulX
    yoffset = ulY
    print("Xoffset, Yoffset = ( %f, %f )" % (xoffset, yoffset))

    # Create a new geomatrix for the image
    geoTrans = list(geoTrans)
    geoTrans[0] = minX
    geoTrans[3] = maxY

    # Map points to pixels for drawing the
    # boundary on a blank 8-bit,
    # black and white, mask image.
    points = []
    pixels = []
    geom = poly.GetGeometryRef()
    pts = geom.GetGeometryRef(0)
    for p in range(pts.GetPointCount()):
        points.append((pts.GetX(p), pts.GetY(p)))
    for p in points:
        pixels.append(world2Pixel(geoTrans, p[0], p[1]))
    rasterPoly = Image.new("L", (pxWidth, pxHeight), 1)
    rasterize = ImageDraw.Draw(rasterPoly)
    rasterize.polygon(pixels, 0)
    mask = imageToArray(rasterPoly)

    # Clip the image using the mask
    clip = gdalnumeric.choose(mask, \
        (clip, 0)).astype(gdalnumeric.uint8)

    # This image has 3 bands so we stretch each one to make them
    # visually brighter
    for i in range(3):
        clip[i, :, :] = stretch(clip[i, :, :])

    # Save new tiff
    #
    #  EDIT: instead of SaveArray, let's break all the
    #  SaveArray steps out more explicity so
    #  we can overwrite the offset of the destination
    #  raster
    #
    ### the old way using SaveArray
    #
    # gdalnumeric.SaveArray(clip, "OUTPUT.tif", format="GTiff",
    #                       prototype=raster_path)
    #
    ###
    #
    gtiffDriver = gdal.GetDriverByName('GTiff')
    if gtiffDriver is None:
        raise ValueError("Can't find GeoTiff Driver")
    gtiffDriver.CreateCopy(
        "OUTPUT.tif",
        OpenArray(clip, prototype_ds=raster_path, xoff=xoffset, yoff=yoffset))

    # Save as an 8-bit jpeg for an easy, quick preview
    clip = clip.astype(gdalnumeric.uint8)
    gdalnumeric.SaveArray(clip, "OUTPUT.jpg", format="JPEG")

    gdal.ErrorReset()

    return (clip, ulX, ulY, geoTrans)
Ejemplo n.º 12
0
def downloadImage(request, result_id, band):
    if request.method == 'GET':
        resultImg = models.QueryResult.objects.filter(pk=result_id).first()
        if resultImg == None:
            raise Http404

        tiles = list(resultImg.tileMatrix)

        src_srs = osr.SpatialReference()
        src_srs.ImportFromWkt(tiles[0].image.wkt)
        tgt_srs = osr.SpatialReference()
        tgt_srs.ImportFromEPSG(4326)
        tgt_srs = src_srs.CloneGeogCS()

        preClipDS, preClipSize, preClipGeoTransform = GetPreClipImage(
            tiles, band, resultImg.imageName, src_srs, tgt_srs)
        # print preClipGeoTransform

        # Raster of input polygons
        rasterPoly = Image.new("L", (preClipSize[0], preClipSize[1]), 1)
        rasterize = ImageDraw.Draw(rasterPoly)

        inputPolygons = resultImg.inputPolygons.polygons

        mostULx = mostLRx = mostULy = mostLRy = None

        for polygon in inputPolygons:
            pixels = []
            inputPolygonReprojected = ReprojectCoords(
                polygon['coordinates'][0], tgt_srs, src_srs)
            for p in inputPolygonReprojected:
                pixels.append(world2Pixel(preClipGeoTransform, p[0], p[1]))

            pixels = intersectPolygonToBorder(pixels, preClipSize[0],
                                              preClipSize[1])
            if pixels is None:
                continue

            print pixels

            if mostULx == None or   \
                mostLRx == None or  \
                mostULy == None or  \
                mostLRy == None:

                mostULx = mostLRx = pixels[0][0]
                mostULy = mostLRy = pixels[0][1]

            for x, y in pixels:
                if x > mostLRx:
                    mostLRx = x
                if x < mostULx:
                    mostULx = x
                if y < mostULy:
                    mostULy = y
                if y > mostLRy:
                    mostLRy = y

            # mostULx, mostULy = world2Pixel(preClipGeoTransform, mostULx, mostULy)
            # mostLRx, mostLRy = world2Pixel(preClipGeoTransform, mostLRx, mostLRy)

            mostULx = 0 if mostULx < 0 else mostULx
            mostLRx = 0 if mostLRx < 0 else mostLRx
            mostULy = 0 if mostULy < 0 else mostULy
            mostLRy = 0 if mostLRy < 0 else mostLRy

            rasterize.polygon(pixels, 0)

        print '%i %i %i %i' % (mostULx, mostULy, mostLRx, mostLRy)

        # clipped the output dataset by minimum rect
        clip = preClipDS.GetRasterBand(1).ReadAsArray(
            0, 0, preClipSize[0], preClipSize[1])[mostULy:mostLRy,
                                                  mostULx:mostLRx]

        # create mask to clip image by polygon
        mask = imageToArray(rasterPoly)[mostULy:mostLRy, mostULx:mostLRx]

        # Clip the image using the mask
        clip = gdalnumeric.choose(mask, (clip, 0)).astype(gdalnumeric.uint16)

        finalFile = NamedTemporaryFile(suffix='.tif',
                                       prefix=resultImg.imageName + '-' +
                                       str(band))
        gdalnumeric.SaveArray(clip, str(finalFile.name), format="GTiff")

        clippedGeoTransform = [
            preClipGeoTransform[0] + mostULx * preClipGeoTransform[1],
            preClipGeoTransform[1], preClipGeoTransform[2],
            preClipGeoTransform[3] + mostULy * preClipGeoTransform[5],
            preClipGeoTransform[4], preClipGeoTransform[5]
        ]

        ds = gdal.Open(str(finalFile.name), gdal.GA_Update)
        ds.SetGeoTransform(clippedGeoTransform)
        ds.SetProjection(src_srs.ExportToWkt())

        # Return HttpResponse Image
        wrapper = FileWrapper(finalFile)
        content_type = mimetypes.guess_type(finalFile.name)[0]
        response = StreamingHttpResponse(wrapper, content_type='content_type')
        response[
            'Content-Disposition'] = "attachment; filename=%s" % finalFile.name

        return response

        # return HttpResponse(json.dumps(dict(out=output_geo_transform,
        #     ext=ext,
        #     finalXSize=finalXSize,
        #     finalYSize=finalYSize)))

    raise Http404
Ejemplo n.º 13
0
'''
Created on Aug 19, 2015

@author: trucvietle
'''

from osgeo import gdalnumeric

src = './data/remote_sensing/FalseColor.tif'
arr = gdalnumeric.LoadFile(src)
gdalnumeric.SaveArray(arr[[1, 0, 2], :],
                      './data/remote_sensing/swap.tif',
                      format='GTiff',
                      prototype=src)
__author__ = 'Fabio'
from osgeo import gdal
raster = gdal.Open("../dati/SatImage/SatImage.tif")
print("Bande :" + str(raster.RasterCount))
print("Pixel in X :" + str(raster.RasterXSize))
print("Pixel in Y :" + str(raster.RasterYSize))

from osgeo import gdalnumeric
srcArray = gdalnumeric.LoadFile("../dati/SatImage/SatImage.tif")
banda1 = srcArray[0]
gdalnumeric.SaveArray(banda1, "../dati/banda1Estratta.jpg", format="JPEG")
Ejemplo n.º 15
0
def main(shapefile_path, raster_path):
    # Load the source data as a gdalnumeric array
    srcArray = gdalnumeric.LoadFile(raster_path)

    # Also load as a gdal image to get geotransform
    # (world file) info
    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()

    # Create an OGR layer from a boundary shapefile
    shapef = ogr.Open(shapefile_path)
    lyr = shapef.GetLayer(
        os.path.split(os.path.splitext(shapefile_path)[0])[1])
    poly = lyr.GetNextFeature()

    # Convert the layer extent to image pixel coordinates
    minX, maxX, minY, maxY = lyr.GetExtent()
    ulX, ulY = world2Pixel(geoTrans, minX, maxY)
    lrX, lrY = world2Pixel(geoTrans, maxX, minY)

    # Calculate the pixel size of the new image
    pxWidth = int(lrX - ulX)
    pxHeight = int(lrY - ulY)

    clip = srcArray[ulY:lrY, ulX:lrX]

    #
    # EDIT: create pixel offset to pass to new image Projection info
    #
    xoffset = ulX
    yoffset = ulY
    print("Xoffset, Yoffset = ( %f, %f )" % (xoffset, yoffset))

    # Create a new geomatrix for the image
    geoTrans = list(geoTrans)
    geoTrans[0] = minX
    geoTrans[3] = maxY

    # Map points to pixels for drawing the
    # boundary on a blank 8-bit,
    # black and white, mask image.
    points = []
    pixels = []
    geom = poly.GetGeometryRef()
    pts = geom.GetGeometryRef(0)
    for p in range(pts.GetPointCount()):
        points.append((pts.GetX(p), pts.GetY(p)))
    for p in points:
        pixels.append(world2Pixel(geoTrans, p[0], p[1]))
    rasterPoly = Image.new("L", (pxWidth, pxHeight), 1)
    rasterize = ImageDraw.Draw(rasterPoly)
    rasterize.polygon(pixels, 0)
    mask = imageToArray(rasterPoly)

    # Clip the image using the mask
    # clip = gdalnumeric.choose(mask, \
    #                           (clip, 0)).astype(gdalnumeric.uint8)
    clip = gdalnumeric.choose(mask, (clip, 0))

    real = np.zeros(clip.shape)
    for i in range(len(clip)):
        for j in range(len(clip[i])):
            val = clip[i][j].real
            if (val < -4):
                val = -4
            real[i, j] = val

    dst_ds = gdal.GetDriverByName('GTiff').Create("hello86568.tif", 300, 300,
                                                  1, gdal.GDT_CFloat32)
    # dst_ds.SetGeoTransform([444720, 30, 0, 3751320, 0, -30])
    raster = np.zeros(real.shape, dtype=np.float32)
    dst_ds.GetRasterBand(1).WriteArray(real)
    # Once we're done, close properly the dataset
    dst_ds = None
    # This image has 3 bands so we stretch each one to make them
    # visually brighter
    # for i in range(3):
    clip2 = stretch(clip)

    # Save new tiff
    #
    #  EDIT: instead of SaveArray, let's break all the
    #  SaveArray steps out more explicity so
    #  we can overwrite the offset of the destination
    #  raster
    #
    ### the old way using SaveArray
    #
    # gdalnumeric.SaveArray(clip, "OUTPUT.tif", format="GTiff", prototype=raster_path)
    #
    ###
    #
    # gtiffDriver = gdal.GetDriverByName('GTiff')
    # if gtiffDriver is None:
    #     raise ValueError("Can't find GeoTiff Driver")
    # gtiffDriver.CreateCopy("beijing9.tif",
    #                        gdal_array.OpenArray(clip, prototype_ds=raster_path)
    #                        )
    # real = np.zeros(clip.shape)
    # for i in range(len(clip)):
    #     for j in range(len(clip[i])):
    #         val = clip[i][j].real
    #         real[i, j] = val
    # draw(real)

    # Save as an 8-bit jpeg for an easy, quick preview
    clip3 = clip2.astype(gdalnumeric.uint8)
    gdalnumeric.SaveArray(clip3, "beijing.jpg", format="JPEG")
    # misc.imsave("beijing7.png", clip2)

    gdal.ErrorReset()
Ejemplo n.º 16
0
def main(shapefile_path, raster_path):
    # Load the source data as a gdalnumeric array
    srcArray = gdalnumeric.LoadFile(raster_path)

    # Also load as a gdal image to get geotransform
    # (world file) info
    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()

    # Create an OGR layer from a boundary shapefile
    shapef = ogr.Open(shapefile_path)
    lyr = shapef.GetLayer(
        os.path.split(os.path.splitext(shapefile_path)[0])[1])
    poly = lyr.GetNextFeature()

    # Convert the layer extent to image pixel coordinates
    minX, maxX, minY, maxY = lyr.GetExtent()
    ulX, ulY = world2Pixel(geoTrans, minX, maxY)
    lrX, lrY = world2Pixel(geoTrans, maxX, minY)

    # Calculate the pixel size of the new image
    pxWidth = int(lrX - ulX)
    pxHeight = int(lrY - ulY)

    clip = srcArray[:, ulY:lrY, ulX:lrX]

    #
    # EDIT: create pixel offset to pass to new image Projection info
    #
    xoffset = ulX
    yoffset = ulY
    print
    "Xoffset, Yoffset = ( %f, %f )" % (xoffset, yoffset)

    # Create a new geomatrix for the image
    geoTrans = list(geoTrans)
    geoTrans[0] = minX
    geoTrans[3] = maxY

    # Map points to pixels for drawing the
    # boundary on a blank 8-bit,
    # black and white, mask image.
    points = []
    pixels = []
    geom = poly.GetGeometryRef()
    pts = geom.GetGeometryRef(0)
    for p in range(pts.GetPointCount()):
        points.append((pts.GetX(p), pts.GetY(p)))
    for p in points:
        pixels.append(world2Pixel(geoTrans, p[0], p[1]))
    rasterPoly = Image.new("L", (pxWidth, pxHeight), 1)
    rasterize = ImageDraw.Draw(rasterPoly)
    rasterize.polygon(pixels, 0)
    mask = imageToArray(rasterPoly)

    # Clip the image using the mask
    clip = gdalnumeric.choose(mask, \
                              (clip, 0)).astype(gdalnumeric.uint8)

    # This image has 3 bands so we stretch each one to make them
    # visually brighter
    for i in range(3):
        clip[i, :, :] = stretch(clip[i, :, :])

    # Save new tiff
    #
    #  EDIT: instead of SaveArray, let's break all the
    #  SaveArray steps out more explicity so
    #  we can overwrite the offset of the destination
    #  raster
    #
    ### the old way using SaveArray
    #
    # gdalnumeric.SaveArray(clip, "OUTPUT.tif", format="GTiff", prototype=raster_path)
    #
    ###
    #
    gtiffDriver = gdal.GetDriverByName('GTiff')
    if gtiffDriver is None:
        raise ValueError("Can't find GeoTiff Driver")
    gtiffDriver.CreateCopy(
        "beijing.tif",
        OpenArray(clip, prototype_ds=raster_path, xoff=xoffset, yoff=yoffset))

    # Save as an 8-bit jpeg for an easy, quick preview
    clip = clip.astype(gdalnumeric.uint8)
    gdalnumeric.SaveArray(clip, "beijing.jpg", format="JPEG")

    gdal.ErrorReset()
Ejemplo n.º 17
0
def process_a_file(shapefile_path,
                   raster_path,
                   outdir,
                   clip_size=448,
                   avg_tree_rds=40):
    shapef = ogr.Open(shapefile_path)
    lyrname = os.path.split(os.path.splitext(shapefile_path)[0])[1]
    lyr = shapef.GetLayer(lyrname)

    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()
    oriHei = srcImage.RasterYSize
    oriWid = srcImage.RasterXSize
    srcArray = gdalnumeric.LoadFile(raster_path)

    feat = lyr.GetNextFeature()
    geoPts = []
    while feat is not None:
        geopt = feat.GetGeometryRef()
        geoPts.append([geopt.GetX(), geopt.GetY()])
        feat = lyr.GetNextFeature()

    out_filename = outdir + lyrname + '_clip_label.txt'
    out_file = open(out_filename, 'a')

    for i, geopt in enumerate(geoPts):
        lyr.ResetReading()
        imgX, imgY = world2Pixel(geoTrans, geopt[0], geopt[1])
        #imgPts.append([imgX, imgY])
        ob_box = [
            imgX - avg_tree_rds, imgY - avg_tree_rds, imgX + avg_tree_rds,
            imgY + avg_tree_rds
        ]
        #ob_boxes.append(ob_box)
        bnd_box = get_bndbox(ob_box, oriWid, oriHei)
        crop = random_crop(oriWid, oriHei, bnd_box, clip_size)
        geoUl = pixel2World(geoTrans, crop[0], crop[1])
        geoBr = pixel2World(geoTrans, crop[2], crop[3])
        lyr.SetSpatialFilterRect(geoUl[0], geoUl[1], geoBr[0], geoBr[1])

        imgPts = []
        ob_boxes = []
        oFeature = lyr.GetNextFeature()

        while oFeature is not None:
            inRectPt = oFeature.GetGeometryRef()
            imgPt = world2Pixel(geoTrans, inRectPt.GetX(), inRectPt.GetY())
            imgPts.append([imgPt[0], imgPt[1]])
            ob_box = [
                imgPt[0] - avg_tree_rds, imgPt[1] - avg_tree_rds,
                imgPt[0] + avg_tree_rds, imgPt[1] + avg_tree_rds
            ]
            ob_boxes.append(ob_box)
            oFeature = lyr.GetNextFeature()
        obs_str, center_str = find_all_objects_in_a_crop(crop,
                                                         imgPts,
                                                         avg_tree_rds,
                                                         oriWid,
                                                         oriHei,
                                                         include_threshold=0.7)

        crop_name = outdir + lyrname + '/' + lyrname + '_ob{}_crop.jpg'.format(
            i)
        record = crop_name + obs_str
        out_file.write(record)
        # Save as an 8-bit jpeg for an easy, quick preview
        clip = srcArray[:, crop[1]:crop[3], crop[0]:crop[2]]
        clip = clip.astype(gdalnumeric.uint8)
        gdalnumeric.SaveArray(clip, crop_name, format="JPEG")
    out_file.close()
Ejemplo n.º 18
0

srcArray = gdalnumeric.LoadFile(raster)
srcImage = gdal.Open(raster)
geoTrans = srcImage.GetGeoTransform()
r = shapefile.Reader('{}.shp'.format(shp))
minX, minY, maxX, maxY = r.bbox
ulX, ulY = world2Pixel(geoTrans, minX, maxY)
lrX, lrY = world2Pixel(geoTrans, maxX, minY)
pxWidth = int(lrX - ulX)
pxHeight = int(lrY - ulY)
clip = srcArray[:, ulY:lrY, ulX:lrX]
geoTrans = list(geoTrans)
geoTrans[0] = minX
geoTrans[3] = maxY

pixels = []
for p in r.shape(0).points:
    pixels.append(world2Pixel(geoTrans, p[0], p[1]))
rasterPoly = Image.new('L', (pxWidth, pxHeight), 1)
rasterize = ImageDraw.Draw(rasterPoly)
rasterize.polygon(pixels, 0)
mask = imageToArray(rasterPoly)

clip = gdalnumeric.numpy.choose(mask,
                                (clip, 0)).astype(gdalnumeric.numpy.uint8)
gdalnumeric.SaveArray(clip,
                      '{}.tif'.format(output),
                      format='GTiff',
                      prototype=raster)