예제 #1
0
 def test_get_area_def_from_raster_extracts_proj_id(self):
     from rasterio.crs import CRS
     from pyresample import utils
     crs = CRS(init='epsg:3857')
     source = tmptiff(crs=crs)
     area_def = utils.get_area_def_from_raster(source)
     self.assertEqual(area_def.proj_id, 'WGS 84 / Pseudo-Mercator')
예제 #2
0
 def test_get_area_def_from_raster(self):
     from rasterio.crs import CRS
     from affine import Affine
     from pyresample import utils
     x_size = 791
     y_size = 718
     transform = Affine(300.0379266750948, 0.0, 101985.0, 0.0,
                        -300.041782729805, 2826915.0)
     crs = CRS(init='epsg:3857')
     source = tmptiff(x_size, y_size, transform, crs=crs)
     area_id = 'area_id'
     proj_id = 'proj_id'
     name = 'name'
     area_def = utils.get_area_def_from_raster(source,
                                               area_id=area_id,
                                               name=name,
                                               proj_id=proj_id)
     self.assertEqual(area_def.area_id, area_id)
     self.assertEqual(area_def.proj_id, proj_id)
     self.assertEqual(area_def.name, name)
     self.assertEqual(area_def.x_size, x_size)
     self.assertEqual(area_def.y_size, y_size)
     self.assertDictEqual(crs.to_dict(), area_def.proj_dict)
     self.assertTupleEqual(
         area_def.area_extent,
         (transform.c, transform.f + transform.e * y_size,
          transform.c + transform.a * x_size, transform.f))
예제 #3
0
    def read(self):
        """Read the image."""
        dataset = rasterio.open(self.finfo['filename'])

        # Create area definition
        if hasattr(dataset, 'crs') and dataset.crs is not None:
            self.area = utils.get_area_def_from_raster(dataset)

        data = xr.open_rasterio(dataset, chunks=(1, CHUNK_SIZE, CHUNK_SIZE))
        attrs = data.attrs.copy()

        # Rename to Satpy convention
        data = data.rename({'band': 'bands'})

        # Rename bands to [R, G, B, A], or a subset of those
        data['bands'] = BANDS[data.bands.size]

        # Mask data if alpha channel is present
        try:
            data = mask_image_data(data)
        except ValueError as err:
            logger.warning(err)

        data.attrs = attrs
        self.file_content['image'] = data
예제 #4
0
 def test_get_area_def_from_raster_non_georef_respects_proj_dict(self):
     from pyresample import utils
     from affine import Affine
     transform = Affine(300.0379266750948, 0.0, 101985.0, 0.0,
                        -300.041782729805, 2826915.0)
     source = tmptiff(transform=transform)
     proj_dict = {'init': 'epsg:3857'}
     area_def = utils.get_area_def_from_raster(source, proj_dict=proj_dict)
     self.assertDictEqual(area_def.proj_dict, proj_dict)
예제 #5
0
    def read(self):
        """Read the image."""
        dataset = rasterio.open(self.finfo['filename'])

        # Create area definition
        if hasattr(dataset, 'crs') and dataset.crs is not None:
            self.area = utils.get_area_def_from_raster(dataset)

        data = xr.open_rasterio(dataset, chunks=(1, CHUNK_SIZE, CHUNK_SIZE))
        attrs = data.attrs.copy()

        # Rename to Satpy convention
        data = data.rename({'band': 'bands'})

        # Rename bands to [R, G, B, A], or a subset of those
        data['bands'] = BANDS[data.bands.size]

        data.attrs = attrs
        self.dataset_name = 'image'
        self.file_content[self.dataset_name] = data
예제 #6
0
def main():
    parser = get_parser()
    args = parser.parse_args()

    levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
    logging.basicConfig(level=levels[min(3, args.verbosity)])

    if args.output_filename is None:
        args.output_filename = [x[:-3] + "png" for x in args.input_tiff]
    else:
        assert len(args.output_filename) == len(
            args.input_tiff
        ), "Output filenames must be equal to number of input tiffs"

    if not (args.add_borders or args.add_coastlines or args.add_grid or args.add_rivers or args.add_colorbar):
        LOG.error("Please specify one of the '--add-X' options to modify the image")
        return -1

    if args.cache_dir and not os.path.isdir(args.cache_dir):
        LOG.info(f"Creating cache directory: {args.cache_dir}")
        os.makedirs(args.cache_dir, exist_ok=True)

    # we may be dealing with large images that look like decompression bombs
    # let's turn off the check for the image size in PIL/Pillow
    Image.MAX_IMAGE_PIXELS = None
    # gather all options into a single dictionary that we can pass to pycoast
    pycoast_options = _args_to_pycoast_dict(args)
    for input_tiff, output_filename in zip(args.input_tiff, args.output_filename):
        LOG.info("Creating {} from {}".format(output_filename, input_tiff))
        img = Image.open(input_tiff)
        img_bands = img.getbands()
        num_bands = len(img_bands)
        # P = palette which we assume to be an RGBA colormap
        img = img.convert("RGBA" if num_bands in (2, 4) or "P" in img_bands else "RGB")
        if pycoast_options:
            area_id = os.path.splitext(input_tiff[0])[0]
            area_def = get_area_def_from_raster(input_tiff, area_id=area_id)
            cw = ContourWriterAGG(args.shapes_dir)
            cw.add_overlay_from_dict(pycoast_options, area_def, background=img)

        if args.add_colorbar:
            from pydecorate import DecoratorAGG

            font_color = args.colorbar_text_color
            font_color = font_color[0] if len(font_color) == 1 else tuple(int(x) for x in font_color)
            font_path = find_font(args.colorbar_font, args.colorbar_text_size)
            # this actually needs an aggdraw font
            font = Font(font_color, font_path, size=args.colorbar_text_size)
            if num_bands not in (1, 2):
                raise ValueError("Can't add colorbar to RGB/RGBA image")

            # figure out what colormap we are dealing with
            rio_ds = rasterio.open(input_tiff)
            input_dtype = np.dtype(rio_ds.meta["dtype"])
            rio_ct = _get_rio_colormap(rio_ds, 1)
            cmap = get_colormap(input_dtype, rio_ct, num_bands)

            # figure out our limits
            vmin = args.colorbar_min
            vmax = args.colorbar_max
            metadata = rio_ds.tags()
            vmin = vmin or metadata.get("min_in")
            vmax = vmax or metadata.get("max_in")
            if isinstance(vmin, str):
                vmin = float(vmin)
            if isinstance(vmax, str):
                vmax = float(vmax)
            if vmin is None or vmax is None:
                vmin = vmin or np.iinfo(input_dtype).min
                vmax = vmax or np.iinfo(input_dtype).max
            cmap.set_range(vmin, vmax)

            dc = DecoratorAGG(img)
            if args.colorbar_align == "top":
                dc.align_top()
            elif args.colorbar_align == "bottom":
                dc.align_bottom()
            elif args.colorbar_align == "left":
                dc.align_left()
            elif args.colorbar_align == "right":
                dc.align_right()

            if args.colorbar_vertical:
                dc.write_vertically()
            else:
                dc.write_horizontally()

            if args.colorbar_width is None or args.colorbar_height is None:
                LOG.warning(
                    "'--colorbar-width' or '--colorbar-height' were " "not specified. Forcing '--colorbar-extend'."
                )
                args.colorbar_extend = True
            kwargs = {}
            if args.colorbar_width:
                kwargs["width"] = args.colorbar_width
            if args.colorbar_height:
                kwargs["height"] = args.colorbar_height
            dc.add_scale(
                cmap,
                extend=args.colorbar_extend,
                font=font,
                line=font_color,
                tick_marks=args.colorbar_tick_marks,
                title=args.colorbar_title,
                unit=args.colorbar_units,
                **kwargs,
            )

        img.save(output_filename)