def handle(self, request): decoder = WMS10GetMapDecoder(request.GET) bbox = decoder.bbox srs = decoder.srs layers = decoder.layers if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( srs, (crss.fromShortCode, crss.fromURN, crss.fromURL) ) if srid is None: raise InvalidCRS(srs, "srs") # WMS 1.1 knows no swapped axes minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx), Trim("y", miny, maxy), ), crs=srs) root_group = lookup_layers(layers, subsets) result, _ = self.renderer.render( root_group, request.GET.items(), subsets=subsets, width=int(decoder.width), height=int(decoder.height) ) return to_http_response(result)
def handle(self, request): decoder = WMS11GetMapDecoder(request.GET) bbox = decoder.bbox time = decoder.time srs = decoder.srs layers = decoder.layers if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( srs, (crss.fromShortCode, crss.fromURN, crss.fromURL) ) if srid is None: raise InvalidCRS(srs, "srs") # WMS 1.1 knows no swapped axes minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx), Trim("y", miny, maxy), ), crs=srs) if time: subsets.append(time) renderer = self.renderer root_group = lookup_layers(layers, subsets, renderer.suffixes) result, _ = renderer.render( root_group, request.GET.items(), time=decoder.time, bands=decoder.dim_bands ) return to_http_response(result)
def handle(self, request): decoder = WMS13GetMapDecoder(request.GET) bbox = decoder.bbox time = decoder.time crs = decoder.crs layers = decoder.layers if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) if srid is None: raise InvalidCRS(crs, "crs") if crss.hasSwappedAxes(srid): miny, minx, maxy, maxx = bbox else: minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx), Trim("y", miny, maxy), ), crs=crs) if time: subsets.append(time) # TODO: adjust way to get to renderer styles = decoder.styles if styles: styles = styles.split(',') from eoxserver.services.ows.wms.layerquery import LayerQuery render_map = LayerQuery().create_map( layers=layers, styles=styles, bbox=bbox, crs=crs, width=decoder.width, height=decoder.height, format=decoder.format, transparent=decoder.transparent, bgcolor=decoder.bgcolor, time=time, range=decoder.dim_range, bands=None, wavelengths=None, elevation=None, cql=decoder.cql, ) from eoxserver.render.mapserver.map_renderer import MapserverMapRenderer return MapserverMapRenderer().render_map(render_map)
def __init__(self, crs_or_srid): if isinstance(crs_or_srid, int): pass elif isinstance(crs_or_srid, basestring): crs_or_srid = parseEPSGCode(crs_or_srid, (fromShortCode, fromURL, fromURN, fromProj4Str)) else: raise ValueError("Unable to obtain CRS from '%s'." % type(crs_or_srid).__name__) self.srid = crs_or_srid
def srid(self): """ Tries to find the correct integer SRID for the crs. """ crs = self.crs if crs is not None: srid = crss.parseEPSGCode( crs, (crss.fromURL, crss.fromURN, crss.fromShortCode)) if srid is None and not crss.is_image_crs(crs): raise InvalidSubsettingCrsException( "Could not parse EPSG code from URI '%s'" % crs) return srid return None
def __init__(self, crs_or_srid, temporary_directory=None): if isinstance(crs_or_srid, int): pass elif isinstance(crs_or_srid, string_types): crs_or_srid = parseEPSGCode( crs_or_srid, (fromShortCode, fromURL, fromURN, fromProj4Str)) else: raise ValueError("Unable to obtain CRS from '%s'." % type(crs_or_srid).__name__) self.srid = crs_or_srid self.temporary_directory = temporary_directory
def parse(cls, raw_value): """ Cast or parse input to its proper represenation.""" if isinstance(raw_value, cls.dtype): if raw_value == 0 or validateEPSGCode(raw_value): return raw_value else: if raw_value == "ImageCRS": return 0 else: value = parseEPSGCode(raw_value, (fromURL, fromURN, fromShortCode)) if value is not None: return value raise ValueError("Invalid CRS %r!" % raw_value)
def get_llbbox(self, bbox, crs): srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) if srid != 4326: poly = Polygon.from_bbox((bbox)) poly.srid = 4326 poly.transform(srid) return poly.extent return bbox
def bbox(self): bbox = self._bbox crs = self.crs srid = crss.parseEPSGCode( self.crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) if srid is None: raise InvalidCRS(crs, "crs") if crss.hasSwappedAxes(srid): miny, minx, maxy, maxx = bbox else: minx, miny, maxx, maxy = bbox return (minx, miny, maxx, maxy)
def get_llbbox(self, bbox, crs): srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL) ) if srid != 4326: poly = Polygon.from_bbox((bbox)) poly.srid = 4326 poly.transform(srid) return poly.extent return bbox
def parse(cls, raw_value): """ Cast or parse input to its proper representation.""" if isinstance(raw_value, cls.dtype): if raw_value == 0 or validateEPSGCode(raw_value): return raw_value else: if raw_value == "ImageCRS": return 0 else: value = parseEPSGCode(raw_value, (fromURL, fromURN, fromShortCode)) if value is not None: return value raise ValueError("Invalid CRS %r!" % raw_value)
def srid(self): """ Tries to find the correct integer SRID for the crs. """ crs = self.crs if crs is not None: srid = crss.parseEPSGCode(crs, (crss.fromURL, crss.fromURN, crss.fromShortCode) ) if srid is None and not crss.is_image_crs(crs): raise InvalidSubsettingException( "Could not parse EPSG code from URI '%s'" % crs ) return srid return None
def xy_srid(self): xy_subsets = filter(lambda s: s.is_x or s.is_y, self) if not len(xy_subsets): return None all_crss = set( map(lambda s: s.crs, xy_subsets) ) if len(all_crss) != 1: raise Exception("All X/Y crss must be the same") xy_crs = iter(all_crss).next() if xy_crs is not None: return crss.parseEPSGCode(xy_crs, (crss.fromURL, crss.fromURN)) return None
def handle(self, request): decoder = WMS13GetMapDecoder(request.GET) bbox = decoder.bbox time = decoder.time crs = decoder.crs layers = decoder.layers if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL) ) if srid is None: raise InvalidCRS(crs, "crs") if crss.hasSwappedAxes(srid): miny, minx, maxy, maxx = bbox else: minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx), Trim("y", miny, maxy), ), crs=crs) if time: subsets.append(time) renderer = self.renderer root_group = lookup_layers(layers, subsets, renderer.suffixes) result, _ = renderer.render( root_group, request.GET.items(), width=int(decoder.width), height=int(decoder.height), time=decoder.time, bands=decoder.dim_bands, subsets=subsets, elevation=decoder.elevation, dimensions=dict( (key[4:], values) for key, values in decoder.dimensions ) ) return to_http_response(result)
def warp_fields(coverages, field_name, bbox, crs, width, height): driver = gdal.GetDriverByName('MEM') out_ds = driver.Create( '', width, height, 1, coverages[0].range_type.get_field(field_name).data_type) out_ds.SetGeoTransform([ bbox[0], (bbox[2] - bbox[0]) / width, 0, bbox[3], 0, -(bbox[3] - bbox[1]) / height, ]) epsg = crss.parseEPSGCode(crs, [crss.fromShortCode]) sr = osr.SpatialReference() sr.ImportFromEPSG(epsg) out_ds.SetProjection(sr.ExportToWkt()) for coverage in coverages: location = coverage.get_location_for_field(field_name) band_index = coverage.get_band_index_for_field(field_name) orig_ds = gdal.open_with_env(location.path, location.env) vrt_filename = None if orig_ds.RasterCount > 1: vrt_filename = '/vsimem/' + uuid4().hex gdal.BuildVRT(vrt_filename, orig_ds, bandList=[band_index]) ds = gdal.Open(vrt_filename) else: ds = orig_ds gdal.Warp(out_ds, ds) ds = None if vrt_filename: gdal.Unlink(vrt_filename) band = out_ds.GetRasterBand(1) return band.ReadAsArray()
def parse_mask(mask_elem): nsmap = {k: v for k, v in iteritems(mask_elem.nsmap) if k} # name = mask_elem.xpath('gml:name/text()', namespaces=nsmap)[0] try: crs = mask_elem.xpath('gml:boundedBy/gml:Envelope/@srsName', namespaces=nsmap)[0] except IndexError: # just return an empty polygon when no mask available return MultiPolygon() srid = crss.parseEPSGCode(crs, [crss.fromURN]) swap = crss.hasSwappedAxes(srid) mask_features = [ parse_polygon(polygon_elem, nsmap, swap) for polygon_elem in mask_elem.xpath( 'eop:maskMembers/eop:MaskFeature/eop:extentOf/gml:Polygon', namespaces=nsmap) ] return MultiPolygon(mask_features, srid=srid)
def handle(self, request): decoder = WMS13GetFeatureInfoDecoder(request.GET) bbox = decoder.bbox time = decoder.time crs = decoder.crs layers = decoder.layers if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) if srid is None: raise InvalidParameterException("Invalid CRS specifier.", "crs") if crss.hasSwappedAxes(srid): miny, minx, maxy, maxx = bbox else: minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx), Trim("y", miny, maxy), ), crs=crs) if time: subsets.append(time) renderer = self.renderer root_group = lookup_layers(layers, subsets, renderer.suffixes) result, _ = renderer.render(root_group, request.GET.items(), request, time=decoder.time, bands=decoder.dim_bands) return to_http_response(result)
def handle(self, request): decoder = WMS13GetMapDecoder(request.GET) bbox = decoder.bbox time = decoder.time crs = decoder.crs layers = decoder.layers elevation = decoder.elevation if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL) ) if srid is None: raise InvalidCRS(crs, "crs") if crss.hasSwappedAxes(srid): miny, minx, maxy, maxx = bbox else: minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx, crs), Trim("y", miny, maxy, crs), )) if time: subsets.append(time) renderer = self.renderer result, _ = renderer.render( layers, (minx, miny, maxx, maxy), crs, (decoder.width, decoder.height), decoder.format, time, elevation, decoder.styles ) return to_http_response(result)
def handle(self, request): decoder = WMS13GetFeatureInfoDecoder(request.GET) bbox = decoder.bbox time = decoder.time crs = decoder.crs layers = decoder.layers if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL) ) if srid is None: raise InvalidParameterException("Invalid CRS specifier.", "crs") if crss.hasSwappedAxes(srid): miny, minx, maxy, maxx = bbox else: minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx), Trim("y", miny, maxy), ), crs=crs) if time: subsets.append(time) renderer = self.renderer root_group = lookup_layers(layers, subsets, renderer.suffixes) result, _ = renderer.render( root_group, request.GET.items(), time=decoder.time, bands=decoder.dim_bands ) return to_http_response(result)
def handle(self, request): decoder = WMS13GetMapDecoder(request.GET) bbox = decoder.bbox time = decoder.time crs = decoder.crs layers = decoder.layers elevation = decoder.elevation if not layers: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) if srid is None: raise InvalidCRS(crs, "crs") if crss.hasSwappedAxes(srid): miny, minx, maxy, maxx = bbox else: minx, miny, maxx, maxy = bbox subsets = Subsets(( Trim("x", minx, maxx, crs), Trim("y", miny, maxy, crs), )) if time: subsets.append(time) renderer = self.renderer result, _ = renderer.render(layers, (minx, miny, maxx, maxy), crs, (decoder.width, decoder.height), decoder.format, time, elevation, decoder.styles) return to_http_response(result)
def convert_GeoTIFF_2_NiFTi(coverage, in_fname, out_fname, bbox, crs): srid = crss.parseEPSGCode(crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) dataset = gdal.Open(in_fname, gdalconst.GA_ReadOnly) in_sr = osr.SpatialReference() in_sr.ImportFromEPSG(4326) # TODO: get real projection value out_sr = osr.SpatialReference() out_sr.ImportFromEPSG(srid) if not in_sr.IsSame(out_sr): raise Exception(dataset.GetProjection()) ct = osr.CoordinateTransformation(out_sr, in_sr) p0 = ct.TransformPoint(bbox[0], bbox[1]) p1 = ct.TransformPoint(bbox[2], bbox[3]) #TODO #gt = dataset.GetGeoTransform() #origin x, offset x1, offset y1, origin y, offset x2, offset y2 image_bbox = coverage.footprint.extent res_x = (image_bbox[2] - image_bbox[0]) / dataset.RasterXSize res_y = (image_bbox[1] - image_bbox[3]) / dataset.RasterYSize bbox[0] = max(image_bbox[0], bbox[0]) bbox[1] = max(image_bbox[1], bbox[1]) bbox[2] = min(image_bbox[2], bbox[2]) bbox[3] = min(image_bbox[3], bbox[3]) r = ( int( math.floor((bbox[0] - image_bbox[0]) / res_x) ), int( math.floor((bbox[3] - image_bbox[3]) / res_y) ), int( math.ceil((bbox[2] - image_bbox[0]) / res_x) ), int( math.ceil((bbox[1] - image_bbox[3]) / res_y) ) ) from ngeo_browse_server.config import models layer = models.Browse.objects.get(coverage_id=coverage.identifier).browse_layer if ('GOME-2' in coverage.identifier or 'NPL3Merged' in coverage.identifier or 'BASCOE' in coverage.identifier or 'LPL2_MIPAS' in coverage.identifier): scale = 1000000 scale_y = res_y scale_x = res_x scale_z = 5 else: scale = 1 scale_y = res_y*200 scale_x = res_x*200 scale_z = 5 if 'GOME-2' in coverage.identifier: layers = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] volume = np.array(dataset.GetRasterBand(2).ReadAsArray(r[0], r[1], r[2]-r[0], r[3]-r[1])*scale ) for i in layers: volume=np.dstack((volume, dataset.GetRasterBand(i).ReadAsArray(r[0], r[1], r[2]-r[0], r[3]-r[1])*scale )) elif 'BASCOE' in coverage.identifier: layers = [9, 13, 17, 19, 21, 24, 27, 28, 29, 31, 33, 34, 35, 37] volume = np.array(dataset.GetRasterBand(4).ReadAsArray(r[0], r[1], r[2]-r[0], r[3]-r[1])*scale ) for i in layers: volume=np.dstack((volume, dataset.GetRasterBand(i).ReadAsArray(r[0], r[1], r[2]-r[0], r[3]-r[1])*scale )) else: volume = np.array(dataset.GetRasterBand(1).ReadAsArray(r[0], r[1], r[2]-r[0], r[3]-r[1])*scale ) for i in range(2, dataset.RasterCount+1): volume=np.dstack((volume, dataset.GetRasterBand(i).ReadAsArray(r[0], r[1], r[2]-r[0], r[3]-r[1])*scale )) volume = np.clip(volume, layer.radiometric_interval_min, layer.radiometric_interval_max) offset = random.uniform(0.00000000000000, 0.00000000000001) scale = np.array([scale_y+offset,scale_x+offset,scale_z+offset,1]) affine = np.diag(scale) img = nib.Nifti1Image(volume, affine) #img = nib.Nifti1Image(volume, np.eye(4)) img.to_filename(out_fname)
def handle(self, request): decoder = self.get_decoder(request) minx, miny, maxx, maxy = decoder.bbox x = decoder.x y = decoder.y time = decoder.time crs = decoder.srs layer_names = decoder.layers width = decoder.width height = decoder.height # calculate the zoomlevel zoom = calculate_zoom((minx, miny, maxx, maxy), width, height, crs) if not layer_names: raise InvalidParameterException("No layers specified", "layers") srid = crss.parseEPSGCode( crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) if srid is None: raise InvalidCRS(crs, "crs") field_mapping, mapping_choices = get_field_mapping_for_model( models.Product) # calculate resolution # TODO: dateline resx = (maxx - minx) / width resy = (maxy - miny) / height p_minx = x * resx p_miny = y * resy p_maxx = (x + 1) * resx p_maxy = (y + 1) * resy filter_expressions = filters.bbox(filters.attribute( 'footprint', field_mapping), p_minx, p_miny, p_maxx, p_maxy, crs, bboverlaps=False) if time: filter_expressions &= filters.time_interval(time) cql = getattr(decoder, 'cql', None) if cql: cql_filters = to_filter(parse(cql), field_mapping, mapping_choices) filter_expressions &= cql_filters # TODO: multiple sorts per layer? sort_by = getattr(decoder, 'sort_by', None) if sort_by: sort_by = (field_mapping.get(sort_by[0], sort_by[0]), sort_by[1]) styles = decoder.styles if styles: styles = styles.split(',') else: styles = [None] * len(layer_names) dimensions = { "time": time, "elevation": decoder.elevation, "ranges": decoder.dim_range, "bands": decoder.dim_bands, "wavelengths": decoder.dim_wavelengths, } feature_info_renderer = get_feature_info_renderer() layer_mapper = LayerMapper( feature_info_renderer.get_supported_layer_types(), "__") layers = [] for layer_name, style in zip(layer_names, styles): name, suffix = layer_mapper.split_layer_suffix_name(layer_name) layer = layer_mapper.lookup_layer(name, suffix, style, filter_expressions, sort_by, zoom=zoom, **dimensions) layers.append(layer) map_ = Map(width=decoder.width, height=decoder.height, format=decoder.format, bbox=(minx, miny, maxx, maxy), crs=crs, bgcolor=decoder.bgcolor, transparent=decoder.transparent, layers=layers) result_bytes, content_type, filename = feature_info_renderer.render_feature_info( map_) response = HttpResponse(result_bytes, content_type=content_type) if filename: response[ 'Content-Disposition'] = 'inline; filename="%s"' % filename return response
def parse_srs_name(srs_name): if not srs_name: return None return crss.parseEPSGCode(srs_name, SRS_PARSERS)
def translate_params(self, params, range_type): """ "Translate" parameters to be understandable by mapserver. """ if params.version.startswith("2.0"): for key, value in params: if key == "interpolation": interpolation = INTERPOLATION_TRANS.get(value) if not interpolation: raise InterpolationMethodNotSupportedException( "Interpolation method '%s' is not supported." % value ) yield key, value else: yield key, value rangesubset = params.rangesubset if rangesubset: yield "rangesubset", ",".join( map(str, rangesubset.get_band_indices(range_type, 1)) ) # TODO: this only works in newer MapServer implementations # (since 6.4?). SCALE_AVAILABLE = ms.msGetVersionInt() > 60401 scalefactor = params.scalefactor if scalefactor is not None: if SCALE_AVAILABLE: yield "scalefactor", str(scalefactor) else: raise RenderException( "'ScaleFactor' is not supported by MapServer in the " "current version.", "scalefactor" ) for scale in params.scales: scaleaxes = [] if isinstance(scale, ScaleSize): yield "size", "%s(%d)" % (scale.axis, scale.size) elif isinstance(scale, ScaleExtent): yield "size", "%s(%d)" % (scale.axis, scale.high-scale.low) elif isinstance(scale, ScaleAxis): if SCALE_AVAILABLE: scaleaxes.append(scale) else: raise RenderException( "'ScaleAxes' is not supported by MapServer in the " "current version.", "scaleaxes" ) if scaleaxes: yield "scaleaxes", ",".join( "%s(%f)" % (scale.axis, scale.value) for scale in scaleaxes ) if params.outputcrs is not None: srid = crss.parseEPSGCode(params.outputcrs, (crss.fromURL, crss.fromURN, crss.fromShortCode) ) if srid is None: raise InvalidOutputCrsException( "Failed to extract an EPSG code from the OutputCRS URI " "'%s'." % params.outputcrs ) yield "outputcrs", params.outputcrs else: for key, value in params: yield key, value
def translate_params(self, params, range_type): """ "Translate" parameters to be understandable by mapserver. """ if params.version.startswith("2.0"): for key, value in params: if key == "interpolation": interpolation = INTERPOLATION_TRANS.get(value) if not interpolation: raise InterpolationMethodNotSupportedException( "Interpolation method '%s' is not supported." % value) yield key, value else: yield key, value rangesubset = params.rangesubset if rangesubset: yield "rangesubset", ",".join( map(str, rangesubset.get_band_indices(range_type, 1))) # TODO: this only works in newer MapServer implementations # (since 6.4?). SCALE_AVAILABLE = ms.msGetVersionInt() > 60401 scalefactor = params.scalefactor if scalefactor is not None: if SCALE_AVAILABLE: yield "scalefactor", str(scalefactor) else: raise RenderException( "'ScaleFactor' is not supported by MapServer in the " "current version.", "scalefactor") for scale in params.scales: scaleaxes = [] if isinstance(scale, ScaleSize): yield "size", "%s(%d)" % (scale.axis, scale.size) elif isinstance(scale, ScaleExtent): yield "size", "%s(%d)" % (scale.axis, scale.high - scale.low) elif isinstance(scale, ScaleAxis): if SCALE_AVAILABLE: scaleaxes.append(scale) else: raise RenderException( "'ScaleAxes' is not supported by MapServer in the " "current version.", "scaleaxes") if scaleaxes: yield "scaleaxes", ",".join("%s(%f)" % (scale.axis, scale.scale) for scale in scaleaxes) if params.outputcrs is not None: srid = crss.parseEPSGCode( params.outputcrs, (crss.fromURL, crss.fromURN, crss.fromShortCode)) if srid is None: raise InvalidOutputCrsException( "Failed to extract an EPSG code from the OutputCRS URI " "'%s'." % params.outputcrs) yield "outputcrs", params.outputcrs else: for key, value in params: yield key, value
def convert_collection_GeoTIFF_2_NiFTi (coverage_collection, out_fname, bbox, crs): srid = crss.parseEPSGCode(crs, (crss.fromShortCode, crss.fromURN, crss.fromURL)) raster_collection = [] dataset = gdal.Open(coverage_collection[0][1], gdalconst.GA_ReadOnly) image_bbox = coverage_collection[0][0].footprint.extent res_x = (image_bbox[2] - image_bbox[0]) / dataset.RasterXSize res_y = (image_bbox[1] - image_bbox[3]) / dataset.RasterYSize size_x = abs(int((bbox[2]-bbox[0])/res_x)) size_y = abs(int((bbox[3]-bbox[1])/res_y)) builder = VRTBuilder(size_x, size_y, len(coverage_collection), coverage_collection[0][0].range_type.bands.all()[0].data_type) for i, (coverage, in_fname) in enumerate(coverage_collection, start=1): dataset = gdal.Open(str(in_fname), gdalconst.GA_ReadOnly) in_sr = osr.SpatialReference() in_sr.ImportFromEPSG(4326) # TODO: get real projection value out_sr = osr.SpatialReference() out_sr.ImportFromEPSG(srid) if not in_sr.IsSame(out_sr): raise Exception(dataset.GetProjection()) ct = osr.CoordinateTransformation(out_sr, in_sr) p0 = ct.TransformPoint(bbox[0], bbox[1]) p1 = ct.TransformPoint(bbox[2], bbox[3]) image_bbox = coverage.footprint.extent res_x = abs(image_bbox[2] - image_bbox[0]) / dataset.RasterXSize res_y = abs(image_bbox[1] - image_bbox[3]) / dataset.RasterYSize dst_rect = ( int( math.floor((image_bbox[0] - bbox[0]) / res_x) ), # x offset int( math.floor((bbox[3] - image_bbox[3]) / res_y) ), # y offset dataset.RasterXSize, # x size dataset.RasterYSize # y size ) builder.add_simple_source(i, str(in_fname), 1, src_rect=(0, 0, dataset.RasterXSize, dataset.RasterYSize), dst_rect=dst_rect) volume = builder.dataset.GetRasterBand(1).ReadAsArray() for i in range(2, len(coverage_collection) + 1): volume = np.dstack((volume, builder.dataset.GetRasterBand(i).ReadAsArray())) offset = random.uniform(0.00000000000000, 0.00000000000001) scale = np.array([res_y*800+offset,res_x*800+offset,res_x*2400+offset,1]) affine = np.diag(scale) img = nib.Nifti1Image(volume, affine) #img = nib.Nifti1Image(volume, np.eye(4)) img.to_filename(out_fname)