def image_to_array(i): ''' Converts a Python Imaging Library (PIL) array to a gdalnumeric image. ''' a = gdalnumeric.fromstring(i.tobytes(), 'b') a.shape = i.im.size[1], i.im.size[0] return a
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 image_to_array_byte(i: Image) -> np.ndarray: """ Converts a Python Imaging Library array to a gdalnumeric image. """ a = gdalnumeric.fromstring(i.tobytes(), dtype=np.int8) a.shape = i.im.size[1], i.im.size[0] return a
def imageToArray(self,i): """ Convert the rasterized clipper shapefile to a mask for use within GDAL. """ a=gdalnumeric.fromstring(i.tostring(),'b') a.shape=i.im.size[1], i.im.size[0] return a
def imageToArray(self, i): """ Convert the rasterized clipper shapefile to a mask for use within GDAL. """ a = gdalnumeric.fromstring(i.tostring(), 'b') a.shape = i.im.size[1], i.im.size[0] return a
def image_to_array(pil_array): """ Converts a Python Imaging Library (PIL) array to a gdalnumeric image. """ gdal_numeric_array = gdalnumeric.fromstring(pil_array.tobytes(), 'b') gdal_numeric_array.shape = pil_array.im.size[1], pil_array.im.size[0] return gdal_numeric_array
def imageToArray(i): """ Converts a Python Imaging Library array to a gdalnumeric image. """ a = gdalnumeric.fromstring(i.tobytes(), 'b') a.shape = i.im.size[1], i.im.size[0] return a
def imageToArray(i): # """ # Converts a Python Imaging Library array to a # gdalnumeric image. # """ # a=gdalnumeric.fromstring(i.tostring(),'b') a = gdalnumeric.fromstring(str(i), 'b') a.shape = i.im.size[1], i.im.size[0] return a
def imageToArray(img): """ 将 PIL.Image 转换为 gdalnumeric array 格式\n 参数:\n img - (PIL.Image)输入图片\n 返回值:\n """ array = gdalnumeric.fromstring(img.tobytes(), 'b') array.shape = img.im.size[1], img.im.size[0] return array
def imageToArray(i): """ 将PIL数组转换成gdalnumeric图像 :param i: :return: """ print(type(i)) # a = gdalnumeric.fromstring(i.tostring(), 'b') a = gdalnumeric.fromstring(i.tobytes(), 'b') a.shape = i.im.size[1], i.im.size[0] return a
def imageToArray(i): a = gdalnumeric.fromstring(i.tobytes(), 'b') a.shape = i.im.size[1], i.im.size[0] return a
def image_to_array(i): """Converts a PIL array to a gdalnumeric image.""" a = gdalnumeric.fromstring(i.tobytes(), 'b') a.shape = i.im.size[1], i.im.size[0] return a
def image_to_array(i): a = gdalnumeric.fromstring(i.tostring(), 'b') a.shape = i.im.size[1], i.im.size[0] return a
def maskShapefile(tile, shp, buffer_size = 0., field = None, value = None, location_id = False): """ Rasterize points, lines or polygons from a shapefile to match ALOS mosaic data. Args: tile: An ALOS tile (biota.LoadTile()) shp: Path to a shapefile consisting of points, lines and/or polygons. This does not have to be in the same projection as ds buffer_size: Optionally specify a buffer to add around features of the shapefile, in meters. field: Optionally specify a single shapefile field to extract (you must also specify its value) value: Optionally specify a single shapefile field value to extract (you must also specify the field name) location_id: Set True to return a unique ID for each masked shape. Note: This is not zero indexed, but starts at 1. Returns: A numpy array with a boolean (or integer) mask delineating locations inside and outside the shapefile and optional buffer. """ import shapefile from osgeo import gdalnumeric assert np.logical_or(np.logical_and(field == None, value == None), np.logical_and(field != None, value != None)), "If specifying field or value, both must be defined. At present, field = %s and value = %s"%(str(field), str(value)) shp = os.path.expanduser(shp) assert os.path.exists(shp), "Shapefile %s does not exist in the file system."%shp # Determine the size of the buffer in degrees buffer_size_degrees = buffer_size / (((tile.xRes * tile.xSize) + (tile.yRes * tile.ySize)) / 2.) # Determine size of buffer to place around lines/polygons buffer_px = int(round(buffer_size_degrees / tile.geo_t[1])) # Create output image. Add a buffer around the image array equal to the maxiumum dilation size. This means that features just outside ALOS tile extent can contribute to dilated mask. rasterPoly = Image.new("I", (tile.xSize + (buffer_px * 2), tile.ySize + (buffer_px * 2)), 0) rasterize = ImageDraw.Draw(rasterPoly) # The shapefile may not have the same CRS as ALOS mosaic data, so this will generate a function to reproject points. coordTransform = _coordinateTransformer(shp) # Read shapefile sf = shapefile.Reader(shp) # Get shapes shapes = np.array(sf.shapes()) # If extracting a mask for just a single field. if field != None: shapes = shapes[getField(shp, field) == value] # For each shape in shapefile... for n, shape in enumerate(shapes): # Get shape bounding box if shape.shapeType == 1 or shape.shapeType == 11: # Points don't have a bbox, calculate manually sxmin = np.min(np.array(shape.points)[:,0]) sxmax = np.max(np.array(shape.points)[:,0]) symin = np.min(np.array(shape.points)[:,1]) symax = np.max(np.array(shape.points)[:,1]) else: sxmin, symin, sxmax, symax = shape.bbox # Transform bounding box points sxmin, symin, z = coordTransform.TransformPoint(sxmin, symin) sxmax, symax, z = coordTransform.TransformPoint(sxmax, symax) # Go to the next record if out of bounds if sxmax < tile.geo_t[0] - buffer_size_degrees: continue if sxmin > tile.geo_t[0] + (tile.geo_t[1] * tile.xSize) + buffer_size_degrees: continue if symax < tile.geo_t[3] + (tile.geo_t[5] * tile.ySize) + buffer_size_degrees: continue if symin > tile.geo_t[3] - buffer_size_degrees: continue #Separate polygons with list indices n_parts = len(shape.parts) #Number of parts indices = shape.parts #Get indices of shapefile part starts indices.append(len(shape.points)) #Add index of final vertex # Catch to allow use of point shapefiles, which don't have parts if shape.shapeType == 1 or shape.shapeType == 11: n_parts = 1 points = shape.points for part in range(n_parts): if shape.shapeType != 1 and shape.shapeType != 11: start_index = shape.parts[part] end_index = shape.parts[part+1] points = shape.points[start_index:end_index] #Map coordinates pixels = [] #Pixel coordinantes # Transform coordinates to pixel values for p in points: # First update points from shapefile projection to ALOS mosaic projection lon, lat, z = coordTransform.TransformPoint(p[0], p[1]) # Then convert map to pixel coordinates using geo transform pixels.append(_world2Pixel(tile.geo_t, lon, lat, buffer_size = buffer_size_degrees)) # Draw the mask for this shape... # if a point... if shape.shapeType == 0 or shape.shapeType == 1 or shape.shapeType == 11: rasterize.point(pixels, n+1) # a line... elif shape.shapeType == 3 or shape.shapeType == 13: rasterize.line(pixels, n+1) # or a polygon. elif shape.shapeType == 5 or shape.shapeType == 15: rasterize.polygon(pixels, n+1) else: print('Shapefile type %s not recognised!'%(str(shape.shapeType))) #Converts a Python Imaging Library array to a gdalnumeric image. mask = gdalnumeric.fromstring(rasterPoly.tobytes(),dtype=np.uint32) mask.shape = rasterPoly.im.size[1], rasterPoly.im.size[0] # If any buffer pixels are slected, dilate the masked area by buffer_px pixels if buffer_px > 0: mask = dilateMask(mask, buffer_px, location_id = location_id) # Get rid of image buffer mask = mask[buffer_px:mask.shape[0]-buffer_px, buffer_px:mask.shape[1]-buffer_px] if location_id == False: # Get rid of record numbers mask = mask > 0 return mask
# рисуем киев на image чтобы сделать mask t1 = timer() points = [] pixels = [] kiev_points = kiev.GetGeometryRef(0) pixels = Stream(range(kiev_points.GetPointCount())) \ .map( lambda i: (kiev_points.GetX(i), kiev_points.GetY(i)) ) \ .map( lambda x, y: world2pixel(transform, x,y) ).list() rasterPoly = Image.new("L", (pxWidth, pxHeight), 1) rasterize = ImageDraw.Draw(rasterPoly) rasterize.polygon(pixels, 0) mask = gdalnumeric.fromstring(rasterPoly.tobytes(),'b') mask.shape=rasterPoly.im.size[1], rasterPoly.im.size[0] print "Create mask %.3f sec" % (timer() - t1) # Clip the image using the mask clip = gdalnumeric.choose(mask, (clip, 0)).astype(gdalnumeric.uint16) gdalnumeric.SaveArray(clip, "kiev.tif", format="GTiff", prototype=raster_path) dataset = gdal.GetDriverByName('GTiff')\ .Create('kiev2.tif', pxWidth, pxHeight, 1, gdal.GDT_Byte) dataset.SetGeoTransform(transform) dataset.SetProjection(str(raster_proj))
def loadShapefile(shp, md_dest, field='', field_values=''): """ Rasterize polygons from a shapefile to match a specified CRS. Args: shp: Path to a shapefile consisting of points, lines and/or polygons. This does not have to be in the same projection as ds. md_dest: A metadata file from sen2mosaic.core.Metadata(). field: Field name to include as part of mask. Defaults to all. If specifying an field, you must also specify an field_value. field_values: Field value or list of values (from 'field') to include in the mask. Defaults to all values. If specifying an field_value, you must also specify a 'field'. Returns: A numpy array with a boolean mask delineating locations inside (True) and outside (False) the shapefile given attribute and attribute_value. """ if field != '' or field_values != '': assert field != '' and field_values != '', "Both `attribute` and `attribute_value` must be specified." shp = os.path.expanduser(shp) assert os.path.exists( shp), "Shapefile %s does not exist in the file system." % shp # Allow input of one or more attribute values if type(field_values) == str: field_values = [field_values] def _coordinateTransformer(shp, EPSG_out): """ Generates function to transform coordinates from a source shapefile CRS to EPSG. Args: shp: Path to a shapefile. Returns: A function that transforms shapefile points to EPSG. """ driver = ogr.GetDriverByName('ESRI Shapefile') ds = driver.Open(shp) layer = ds.GetLayer() spatialRef = layer.GetSpatialRef() # Create coordinate transformation inSpatialRef = osr.SpatialReference() inSpatialRef.ImportFromWkt(spatialRef.ExportToWkt()) outSpatialRef = osr.SpatialReference() outSpatialRef.ImportFromEPSG(EPSG_out) coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef) return coordTransform def _world2Pixel(geo_t, x, y): """ Uses a gdal geomatrix (ds.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate. Modified from: http://geospatialpython.com/2011/02/clip-raster-using-shapefile.html. Args: geo_t: A gdal geoMatrix (ds.GetGeoTransform(). x: x coordinate in map units. y: y coordinate in map units. buffer_size: Optionally specify a buffer size. This is used when a buffer has been applied to extend all edges of an image, as in rasterizeShapfile(). Returns: A tuple with pixel/line locations for each input coordinate. """ ulX = geo_t[0] ulY = geo_t[3] xDist = geo_t[1] yDist = geo_t[5] pixel = int((x - ulX) / xDist) line = int((y - ulY) / yDist) return (pixel, line) def _getField(shp, field): ''' Get values from a field in a shapefile attribute table. Args: shp: A string pointing to a shapefile field: A string with the field name of the attribute of interest Retuns: An array containing all the values of the specified attribute ''' assert os.path.isfile(shp), "Shapefile %s does not exist." % shp # Read shapefile sf = shapefile.Reader(shp) # Get the column number of the field of interest for n, this_field in enumerate(sf.fields[1:]): fieldname = this_field[0] if fieldname == field: field_n = n assert 'field_n' in locals( ), "Attribute %s not found in shapefile." % str(field) # Extract data type from shapefile. Interprets N (int), F (float) and C (string), sets others to string. this_dtype = sf.fields[1:][field_n][1] if this_dtype == 'N': dtype = np.int elif this_dtype == 'F': dtype = np.float32 elif this_dtype == 'C': dtype = np.str else: dtype = np.str value_out = [] # Cycle through records: for s in sf.records(): value_out.append(s[field_n]) return np.array(value_out, dtype=dtype) # Create output image rasterPoly = Image.new("I", (md_dest.ncols, md_dest.nrows), 0) rasterize = ImageDraw.Draw(rasterPoly) # The shapefile may not have the same CRS as the data, so this will generate a function to reproject points. coordTransform = _coordinateTransformer(shp, md_dest.EPSG_code) # Read shapefile sf = shapefile.Reader(shp) # Get names of fields fields = sf.fields[1:] field_names = [field[0] for field in fields] # Get shapes shapes = np.array(sf.shapes()) # If extracting a mask for just a single field. if field != '': shape_values = _getField(shp, field) field_values = np.array(field_values).astype(shape_values.dtype) shapes = shapes[np.isin(shape_values, field_values)] # For each shape in shapefile... for n, shape in enumerate(shapes): #if field != '' and shape_values[n] not in field_values: # continue # Get shape bounding box if shape.shapeType == 1 or shape.shapeType == 11: # Points don't have a bbox, calculate manually sxmin = np.min(np.array(shape.points)[:, 0]) sxmax = np.max(np.array(shape.points)[:, 0]) symin = np.min(np.array(shape.points)[:, 1]) symax = np.max(np.array(shape.points)[:, 1]) else: sxmin, symin, sxmax, symax = shape.bbox # Transform points sxmin, symin, z = coordTransform.TransformPoint(sxmin, symin) sxmax, symax, z = coordTransform.TransformPoint(sxmax, symax) # Go to the next record if out of bounds geo_t = md_dest.geo_t if sxmax < geo_t[0]: continue if sxmin > geo_t[0] + (geo_t[1] * md_dest.ncols): continue if symax < geo_t[3] + (geo_t[5] * md_dest.nrows): continue if symin > geo_t[3]: continue #Separate polygons with list indices n_parts = len(shape.parts) #Number of parts indices = shape.parts #Get indices of shapefile part starts indices.append(len(shape.points)) #Add index of final vertex for part in range(n_parts): if shape.shapeType != 1 and shape.shapeType != 11: start_index = shape.parts[part] end_index = shape.parts[part + 1] points = shape.points[start_index:end_index] #Map coordinates pixels = [] #Pixel coordinantes # Transform coordinates to pixel values for p in points: # First update points from shapefile projection to image projection x, y, z = coordTransform.TransformPoint(p[0], p[1]) # Then convert map to pixel coordinates using geo transform pixels.append(_world2Pixel(md_dest.geo_t, x, y)) # Draw the mask for this shape... # if a point... if shape.shapeType == 0 or shape.shapeType == 1 or shape.shapeType == 11: rasterize.point(pixels, n + 1) # a line... elif shape.shapeType == 3 or shape.shapeType == 13: rasterize.line(pixels, n + 1) # or a polygon. elif shape.shapeType == 5 or shape.shapeType == 15: rasterize.polygon(pixels, n + 1) else: print('Shapefile type %s not recognised!' % (str(shape.shapeType))) #Converts a Python Imaging Library array to a gdalnumeric image. mask = gdalnumeric.fromstring(rasterPoly.tobytes(), dtype=np.uint32) mask.shape = rasterPoly.im.size[1], rasterPoly.im.size[0] return mask
def pilArrayToGDALnumeric(self, pA): gdalArray=gdalnumeric.fromstring(pA.tostring(),'b') gdalArray=shape=pA.im.size[1], pA.im.size[0] return a