Example #1
0
    def test_add_shapefile_shapes(self):
        grid_img = Image.open(os.path.join(os.path.dirname(__file__),
                                           'brazil_shapefiles.png'))
        grid_data = np.array(grid_img)

        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=merc +lon_0=-60 +lat_ts=-30.0 +a=6371228.0 +units=m'
        area_extent = (-2000000.0, -5000000.0, 5000000.0, 2000000.0)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines(img, area_def, resolution='l', level=4)
        cw.add_shapefile_shapes(img, area_def,
                                os.path.join(os.path.dirname(__file__), 'test_data/shapes/Metareas.shp'),
                                outline='red')
        cw.add_shapefile_shape(img, area_def,
                               os.path.join(os.path.dirname(__file__),
                                            'test_data/shapes/divisao_politica/BR_Regioes.shp'), 3,
                               outline='blue')
        cw.add_shapefile_shape(img, area_def,
                               os.path.join(os.path.dirname(__file__),
                                            'test_data/shapes/divisao_politica/BR_Regioes.shp'), 4,
                               outline='blue', fill='green')

        res = np.array(img)
        self.failUnless(fft_metric(grid_data, res), 'Writing of Brazil shapefiles failed')
Example #2
0
    def test_grid_geos(self):
        geos_img = Image.open(os.path.join(os.path.dirname(__file__), 'grid_geos.png'))
        geos_data = np.array(geos_img)
        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=geos +lon_0=0.0 +a=6378169.00 +b=6356583.80 +h=35785831.0'
        area_extent = (-5570248.4773392612, -5567248.074173444, 5567248.074173444, 5570248.4773392612)
        area_def = (proj4_string, area_extent)
        cw = ContourWriter(gshhs_root_dir)
        cw.add_coastlines(img, area_def, resolution='l')
        cw.add_grid(img, area_def, (10.0, 10.0), (2.0, 2.0), fill='blue', outline='blue', minor_outline='blue',
                    write_text=False)

        res = np.array(img)
        self.failUnless(fft_metric(geos_data, res), 'Writing of geos contours failed')
Example #3
0
    def test_geos(self):
        geos_img = Image.open(
            os.path.join(os.path.dirname(__file__), 'contours_geos.png'))
        geos_data = np.array(geos_img)

        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=geos +lon_0=0.0 +a=6378169.00 +b=6356583.80 +h=35785831.0'
        area_extent = (-5570248.4773392612, -5567248.074173444,
                       5567248.074173444, 5570248.4773392612)
        area_def = (proj4_string, area_extent)
        cw = ContourWriter(gshhs_root_dir)
        cw.add_coastlines(img, area_def, resolution='l')

        res = np.array(img)
        self.failUnless(fft_metric(geos_data, res),
                        'Writing of geos contours failed')
Example #4
0
    def test_add_polygon(self):
        grid_img = Image.open(os.path.join(os.path.dirname(__file__),
                                           'nh_polygons.png'))
        grid_data = np.array(grid_img)
        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=laea +lat_0=90 +lon_0=0 +a=6371228.0 +units=m'
        area_extent = (-5326849.0625, -5326849.0625, 5326849.0625, 5326849.0625)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        polygons = {
            'REYKJAVIK_ATC_A': ((-20.0, 73.0), (0.0, 73.0), (0.0, 61.0), (-30.0, 61.0), (-39.0, 63.5), (-20, 70)),
            'REYKJAVIK_ATC_B': (
            (-39, 63.5), (-55 + 4 / 6.0, 63.5), (-57 + 45 / 60.0, 65), (-76, 76), (-75, 78), (-60, 82), (0, 90),
            (30, 82), (0, 82), (0, 73), (-20, 73), (-20,
                                                    70)),
            'REYKJAVIK_ATC':   (
            (0.0, 73.0), (0.0, 61.0), (-30.0, 61.0), (-39, 63.5), (-55 + 4 / 6.0, 63.5), (-57 + 45 / 60.0, 65),
            (-76, 76), (-75, 78), (-60, 82), (0, 90), (30, 82), (0, 82)),
            'ICELAND_BOX':     ((-25, 62.5), (-25, 67), (-13, 67), (-13, 62.5))
        }

        cw.add_polygon(img, area_def, polygons['REYKJAVIK_ATC'], outline='red')
        cw.add_polygon(img, area_def, polygons['ICELAND_BOX'], outline='green', fill='gray')
        cw.add_coastlines(img, area_def, resolution='l', level=4)

        res = np.array(img)
        self.failUnless(fft_metric(grid_data, res), 'Writing of nh polygons failed')
Example #5
0
    def test_grid_file(self):
        grid_img = Image.open(os.path.join(os.path.dirname(__file__),
                                           'grid_europe.png'))
        grid_data = np.array(grid_img)
        proj4_string = '+proj=stere +lon_0=8.00 +lat_0=50.00 +lat_ts=50.00 +ellps=WGS84'
        area_extent = (-3363403.31, -2291879.85, 2630596.69, 2203620.1)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines_to_file(grid_file, area_def, resolution='l', level=4)
        font = ImageFont.truetype(os.path.join(os.path.dirname(__file__), 'test_data', 'DejaVuSerif.ttf'), 16)
        cw.add_grid_to_file(grid_file, area_def, (10.0, 10.0), (2.0, 2.0), font=font, fill='blue',
                            outline='blue', minor_outline='blue')

        img = Image.open(grid_file)
        res = np.array(img)
        self.failUnless(fft_metric(grid_data, res), 'Writing of grid failed')
Example #6
0
    def test_grid_nh(self):
        grid_img = Image.open(os.path.join(os.path.dirname(__file__),
                                           'grid_nh.png'))
        grid_data = np.array(grid_img)
        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=laea +lat_0=90 +lon_0=0 +a=6371228.0 +units=m'
        area_extent = (-5326849.0625, -5326849.0625, 5326849.0625, 5326849.0625)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines(img, area_def, resolution='l', level=4)
        font = ImageFont.truetype(os.path.join(os.path.dirname(__file__), 'test_data', 'DejaVuSerif.ttf'), 10)
        cw.add_grid(img, area_def, (10.0, 10.0), (2.0, 2.0), font=font, fill='blue',
                    outline='blue', minor_outline='blue',
                    lon_placement='tblr', lat_placement='')

        res = np.array(img)
        self.failUnless(fft_metric(grid_data, res), 'Writing of nh grid failed')
Example #7
0
    def test_dateline_boundary_cross(self):
        dl_img = Image.open(os.path.join(os.path.dirname(__file__),
                                         'dateline_boundary_cross.png'))
        dl_data = np.array(dl_img)

        img = Image.new('RGB', (640, 480))
        proj4_string = '+proj=stere +lon_0=140.00 +lat_0=60.00 +lat_ts=50.00 +ellps=WGS84'
        area_extent = (-3363403.31, -2291879.85, 2630596.69, 2203620.1)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines(img, area_def, resolution='l', level=4)
        font = ImageFont.truetype(os.path.join(os.path.dirname(__file__), 'test_data', 'DejaVuSerif.ttf'), 16)
        cw.add_grid(img, area_def, (10.0, 10.0), (2.0, 2.0), font=font, fill='blue',
                    outline='blue', minor_outline='blue',
                    lon_placement='b', lat_placement='lr')

        res = np.array(img)
        self.failUnless(fft_metric(dl_data, res), 'Writing of dateline boundary crossing data failed')
Example #8
0
    def __init__(self, config):
        self.config = config
        topics = config.sections()
        self.listener = ListenerContainer(topics=topics)
        self._loop = True

        if GSHHS_DATA_ROOT:
            self._cw = ContourWriter(GSHHS_DATA_ROOT)
        else:
            self._cw = None
        self._force_gc = False
Example #9
0
    def add_overlay_config(self, config_file):
        """Add overlay to image parsing a configuration file.
           
        """

        import ConfigParser

        conf = ConfigParser.ConfigParser()
        conf.read(os.path.join(CONFIG_PATH, "satpy.cfg"))

        coast_dir = conf.get('shapes', 'dir')

        logger.debug("Getting area for overlay: " + str(self.area.area_id))

        try:
            import aggdraw
            from pycoast import ContourWriterAGG

            cw_ = ContourWriterAGG(coast_dir)
        except ImportError:
            logger.warning(
                "AGGdraw lib not installed...width and opacity properties are not available for overlays."
            )
            from pycoast import ContourWriter

            cw_ = ContourWriter(coast_dir)

        logger.debug("Getting area for overlay: " + str(self.area))

        if self.area is None:
            raise ValueError("Area of image is None, can't add overlay.")

        if self.mode != "RGB":
            self.convert("RGB")

        img = self.pil_image()

        from satpy.projector import get_area_def

        if isinstance(self.area, str):
            self.area = get_area_def(self.area)
        logger.info("Add overlays to image.")
        logger.debug("Area = " + str(self.area.area_id))

        foreground = cw_.add_overlay_from_config(config_file, self.area)
        img.paste(foreground, mask=foreground.split()[-1])

        arr = np.array(img)

        if len(self.channels) == 1:
            self.channels[0] = np.ma.array(arr[:, :] / 255.0)
        else:
            for idx in range(len(self.channels)):
                self.channels[idx] = np.ma.array(arr[:, :, idx] / 255.0)
Example #10
0
    def test_grid_file(self):
        grid_img = Image.open(
            os.path.join(os.path.dirname(__file__), 'grid_europe.png'))
        grid_data = np.array(grid_img)
        proj4_string = \
            '+proj=stere +lon_0=8.00 +lat_0=50.00 +lat_ts=50.00 +ellps=WGS84'
        area_extent = (-3363403.31, -2291879.85, 2630596.69, 2203620.1)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines_to_file(grid_file, area_def, resolution='l', level=4)
        font = ImageFont.truetype(
            os.path.join(os.path.dirname(__file__), 'test_data',
                         'DejaVuSerif.ttf'), 16)
        cw.add_grid_to_file(grid_file,
                            area_def, (10.0, 10.0), (2.0, 2.0),
                            font=font,
                            fill='blue',
                            write_text=False,
                            outline='blue',
                            minor_outline='blue')

        img = Image.open(grid_file)
        res = np.array(img)
        self.assertTrue(fft_metric(grid_data, res), 'Writing of grid failed')
Example #11
0
    def test_dateline_boundary_cross(self):
        dl_img = Image.open(
            os.path.join(os.path.dirname(__file__),
                         'dateline_boundary_cross.png'))
        dl_data = np.array(dl_img)

        img = Image.new('RGB', (640, 480))
        proj4_string = '+proj=stere +lon_0=140.00 +lat_0=60.00 +lat_ts=50.00 +ellps=WGS84'
        area_extent = (-3363403.31, -2291879.85, 2630596.69, 2203620.1)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines(img, area_def, resolution='l', level=4)
        font = ImageFont.truetype(
            os.path.join(os.path.dirname(__file__), 'test_data',
                         'DejaVuSerif.ttf'), 16)
        cw.add_grid(img,
                    area_def, (10.0, 10.0), (2.0, 2.0),
                    font=font,
                    fill='blue',
                    outline='blue',
                    minor_outline='blue',
                    lon_placement='b',
                    lat_placement='lr')

        res = np.array(img)
        self.failUnless(fft_metric(dl_data, res),
                        'Writing of dateline boundary crossing data failed')
Example #12
0
    def test_grid_nh(self):
        grid_img = Image.open(
            os.path.join(os.path.dirname(__file__), 'grid_nh.png'))
        grid_data = np.array(grid_img)
        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=laea +lat_0=90 +lon_0=0 +a=6371228.0 +units=m'
        area_extent = (-5326849.0625, -5326849.0625, 5326849.0625,
                       5326849.0625)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines(img, area_def, resolution='l', level=4)
        font = ImageFont.truetype(
            os.path.join(os.path.dirname(__file__), 'test_data',
                         'DejaVuSerif.ttf'), 10)
        cw.add_grid(img,
                    area_def, (10.0, 10.0), (2.0, 2.0),
                    font=font,
                    fill='blue',
                    outline='blue',
                    minor_outline='blue',
                    lon_placement='tblr',
                    lat_placement='')

        res = np.array(img)
        self.failUnless(fft_metric(grid_data, res),
                        'Writing of nh grid failed')
Example #13
0
    def test_add_shapefile_shapes(self):
        grid_img = Image.open(
            os.path.join(os.path.dirname(__file__), 'brazil_shapefiles.png'))
        grid_data = np.array(grid_img)

        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=merc +lon_0=-60 +lat_ts=-30.0 +a=6371228.0 +units=m'
        area_extent = (-2000000.0, -5000000.0, 5000000.0, 2000000.0)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        cw.add_coastlines(img, area_def, resolution='l', level=4)
        cw.add_shapefile_shapes(img,
                                area_def,
                                os.path.join(os.path.dirname(__file__),
                                             'test_data/shapes/Metareas.shp'),
                                outline='red')
        cw.add_shapefile_shape(
            img,
            area_def,
            os.path.join(os.path.dirname(__file__),
                         'test_data/shapes/divisao_politica/BR_Regioes.shp'),
            3,
            outline='blue')
        cw.add_shapefile_shape(
            img,
            area_def,
            os.path.join(os.path.dirname(__file__),
                         'test_data/shapes/divisao_politica/BR_Regioes.shp'),
            4,
            outline='blue',
            fill='green')

        res = np.array(img)
        self.assertTrue(fft_metric(grid_data, res),
                        'Writing of Brazil shapefiles failed')
Example #14
0
    def test_europe(self):
        euro_img = Image.open(
            os.path.join(os.path.dirname(__file__), 'contours_europe.png'))
        euro_data = np.array(euro_img)

        img = Image.new('RGB', (640, 480))
        proj4_string = '+proj=stere +lon_0=8.00 +lat_0=50.00 +lat_ts=50.00 +ellps=WGS84'
        area_extent = (-3363403.31, -2291879.85, 2630596.69, 2203620.1)
        area_def = (proj4_string, area_extent)
        cw = ContourWriter(gshhs_root_dir)
        cw.add_coastlines(img, area_def, resolution='l', level=4)
        cw.add_rivers(img, area_def, level=5, outline='blue')
        cw.add_borders(img, area_def, outline=(255, 0, 0))

        res = np.array(img)
        self.failUnless(fft_metric(euro_data, res),
                        'Writing of contours failed')
Example #15
0
    def test_europe(self):
        euro_img = Image.open(os.path.join(os.path.dirname(__file__),
                                           'contours_europe.png'))
        euro_data = np.array(euro_img)

        img = Image.new('RGB', (640, 480))
        proj4_string = '+proj=stere +lon_0=8.00 +lat_0=50.00 +lat_ts=50.00 +ellps=WGS84'
        area_extent = (-3363403.31, -2291879.85, 2630596.69, 2203620.1)
        area_def = (proj4_string, area_extent)
        cw = ContourWriter(gshhs_root_dir)
        cw.add_coastlines(img, area_def, resolution='l', level=4)
        cw.add_rivers(img, area_def, level=5, outline='blue')
        cw.add_borders(img, area_def, outline=(255, 0, 0))

        res = np.array(img)
        self.failUnless(fft_metric(euro_data, res), 'Writing of contours failed')
Example #16
0
    def test_add_polygon(self):
        grid_img = Image.open(
            os.path.join(os.path.dirname(__file__), 'nh_polygons.png'))
        grid_data = np.array(grid_img)
        img = Image.new('RGB', (425, 425))
        proj4_string = '+proj=laea +lat_0=90 +lon_0=0 +a=6371228.0 +units=m'
        area_extent = (-5326849.0625, -5326849.0625, 5326849.0625,
                       5326849.0625)
        area_def = (proj4_string, area_extent)

        cw = ContourWriter(gshhs_root_dir)

        polygons = {
            'REYKJAVIK_ATC_A': ((-20.0, 73.0), (0.0, 73.0), (0.0, 61.0),
                                (-30.0, 61.0), (-39.0, 63.5), (-20, 70)),
            'REYKJAVIK_ATC_B':
            ((-39, 63.5), (-55 + 4 / 6.0, 63.5), (-57 + 45 / 60.0, 65),
             (-76, 76), (-75, 78), (-60, 82), (0, 90), (30, 82), (0, 82),
             (0, 73), (-20, 73), (-20, 70)),
            'REYKJAVIK_ATC':
            ((0.0, 73.0), (0.0, 61.0), (-30.0, 61.0), (-39, 63.5),
             (-55 + 4 / 6.0, 63.5), (-57 + 45 / 60.0, 65), (-76, 76),
             (-75, 78), (-60, 82), (0, 90), (30, 82), (0, 82)),
            'ICELAND_BOX': ((-25, 62.5), (-25, 67), (-13, 67), (-13, 62.5))
        }

        cw.add_polygon(img, area_def, polygons['REYKJAVIK_ATC'], outline='red')
        cw.add_polygon(img,
                       area_def,
                       polygons['ICELAND_BOX'],
                       outline='green',
                       fill='gray')
        cw.add_coastlines(img, area_def, resolution='l', level=4)

        res = np.array(img)
        self.assertTrue(fft_metric(grid_data, res),
                        'Writing of nh polygons failed')
Example #17
0
    def test_grid_geos(self):
        geos_img = Image.open(
            os.path.join(os.path.dirname(__file__), 'grid_geos.png'))
        geos_data = np.array(geos_img)
        img = Image.new('RGB', (425, 425))
        proj4_string = \
            '+proj=geos +lon_0=0.0 +a=6378169.00 +b=6356583.80 +h=35785831.0'
        area_extent = (-5570248.4773392612, -5567248.074173444,
                       5567248.074173444, 5570248.4773392612)
        area_def = (proj4_string, area_extent)
        cw = ContourWriter(gshhs_root_dir)
        cw.add_coastlines(img, area_def, resolution='l')
        cw.add_grid(img,
                    area_def, (10.0, 10.0), (2.0, 2.0),
                    fill='blue',
                    outline='blue',
                    minor_outline='blue',
                    write_text=False)

        res = np.array(img)
        self.assertTrue(fft_metric(geos_data, res),
                        'Writing of geos contours failed')
Example #18
0
    proj4_string = "+" + \
        " +".join(("proj=" + proj + ",lat_0=" + str(lat_0) + ",lon_0=" + str(lon_0) + ",ellps=WGS84").split(","))

    print proj4_string

    print "REGION:", name, "{"
    print "\tNAME:\t", name
    print "\tPCS_ID:\t", proj + "_" + str(lon_0) + "_" + str(lat_0)
    print ("\tPCS_DEF:\tproj=" + proj +
           ",lat_0=" + str(lat_0) +
           ",lon_0=" + str(lon_0) +
           ",ellps=WGS84")
    print "\tXSIZE:\t", xsize
    print "\tYSIZE:\t", ysize
    print "\tAREA_EXTENT:\t", area_extent
    print "};"

    if args.shapes is None:
        sys.exit(0)
    from PIL import Image
    from pycoast import ContourWriter
    img = Image.new('RGB', (xsize, ysize))
    #proj4_string = '+proj=geos +lon_0=0.0 +a=6378169.00 +b=6356583.80 +h=35785831.0'
    #area_extent = (-5570248.4773392612, -5567248.074173444, 5567248.074173444, 5570248.4773392612)
    area_def = (proj4_string, area_extent)
    cw = ContourWriter(args.shapes)
    #cw = ContourWriterAGG('/usr/share/gshhg-gmt-shp/')
    cw.add_coastlines(img, (proj4_string, area_extent), resolution='l')

    img.save('test.png')
Example #19
0
    )

    scn.load(['sea_surface_temperature'])
    lcd = scn.resample('euro4', radius_of_influence=2000)

    sstdata = lcd['sea_surface_temperature'][:]
    import numpy as np
    arr = np.ma.where(np.less_equal(sstdata, 0), 0, sstdata - 273.15)

    # Convert sst to numbers between 0 and 28, corresponding to the lut:
    data = np.ma.where(np.less(arr, 0), 28, 28.0 - arr)
    data = np.ma.where(np.greater(arr, 23.0), 4, data).round().astype('uint8')

    from trollimage.image import Image
    from satpy.imageo import palettes
    palette = palettes.sstlut_osisaf_metno()

    img = Image(data, mode='P', palette=palette)
    img.show()
    img.save('osisaf_sst_viirs_satpy.png')

    from pycoast import ContourWriter

    cw_ = ContourWriter('/home/a000680/data/shapes')
    pilim = img.pil_image()
    area_def = lcd['sea_surface_temperature'].info['area']
    cw_.add_coastlines(
        pilim, area_def, resolution='i', level=1, outline=(220, 220, 220))
    pilim.show()
    pilim.save('./osisaf_sst_viirs_satpy_withovl.png')
Example #20
0
    ysize = int((area_extent[3] - area_extent[1]) / res)

    proj4_string = "+" + \
        " +".join(("proj=" + proj + ",lat_0=" + str(lat_0) + ",lon_0=" + str(lon_0) + ",ellps=WGS84").split(","))

    print proj4_string

    print "REGION:", name, "{"
    print "\tNAME:\t", name
    print "\tPCS_ID:\t", proj + "_" + str(lon_0) + "_" + str(lat_0)
    print("\tPCS_DEF:\tproj=" + proj + ",lat_0=" + str(lat_0) + ",lon_0=" +
          str(lon_0) + ",ellps=WGS84")
    print "\tXSIZE:\t", xsize
    print "\tYSIZE:\t", ysize
    print "\tAREA_EXTENT:\t", area_extent
    print "};"

    if args.shapes is None:
        sys.exit(0)
    from PIL import Image
    from pycoast import ContourWriter
    img = Image.new('RGB', (xsize, ysize))
    #proj4_string = '+proj=geos +lon_0=0.0 +a=6378169.00 +b=6356583.80 +h=35785831.0'
    #area_extent = (-5570248.4773392612, -5567248.074173444, 5567248.074173444, 5570248.4773392612)
    area_def = (proj4_string, area_extent)
    cw = ContourWriter(args.shapes)
    #cw = ContourWriterAGG('/usr/share/gshhg-gmt-shp/')
    cw.add_coastlines(img, (proj4_string, area_extent), resolution='l')

    img.save('test.png')
Example #21
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):
        LOG.error(
            "Please specify one of the '--add-X' options to modify the image")
        return -1

    for input_tiff, output_filename in zip(args.input_tiff,
                                           args.output_filename):
        LOG.info("Creating {} from {}".format(output_filename, input_tiff))
        gtiff = gdal.Open(input_tiff)
        proj4_str = osr.SpatialReference(gtiff.GetProjection()).ExportToProj4()
        ul_x, res_x, _, ul_y, _, res_y = gtiff.GetGeoTransform()
        half_pixel_x = res_x / 2.
        half_pixel_y = res_y / 2.
        area_extent = (
            ul_x - half_pixel_x,  # lower-left X
            ul_y + res_y * gtiff.RasterYSize - half_pixel_y,  # lower-left Y
            ul_x + res_x * gtiff.RasterXSize + half_pixel_x,  # upper-right X
            ul_y + half_pixel_y,  # upper-right Y
        )
        p = Proj(proj4_str)
        if p.is_latlong():
            # convert lat/lons to radians
            area_extent = p(area_extent[0], area_extent[1]) + p(
                area_extent[2], area_extent[3])
        img = Image.open(input_tiff).convert('RGB')
        area_def = (proj4_str, area_extent)

        cw = ContourWriter(args.shapes_dir)

        if args.add_coastlines:
            outline = args.coastlines_outline[0] if len(
                args.coastlines_outline) == 1 else tuple(
                    int(x) for x in args.coastlines_outline)
            if args.coastlines_fill:
                fill = args.coastlines_fill[0] if len(
                    args.coastlines_fill) == 1 else tuple(
                        int(x) for x in args.coastlines_fill)
            else:
                fill = None
            cw.add_coastlines(img,
                              area_def,
                              resolution=args.coastlines_resolution,
                              level=args.coastlines_level,
                              outline=outline,
                              fill=fill)

        if args.add_rivers:
            outline = args.rivers_outline[0] if len(
                args.rivers_outline) == 1 else tuple(
                    int(x) for x in args.rivers_outline)
            cw.add_rivers(img,
                          area_def,
                          resolution=args.rivers_resolution,
                          level=args.rivers_level,
                          outline=outline)

        if args.add_borders:
            outline = args.borders_outline[0] if len(
                args.borders_outline) == 1 else tuple(
                    int(x) for x in args.borders_outline)
            cw.add_borders(img,
                           area_def,
                           resolution=args.borders_resolution,
                           level=args.borders_level,
                           outline=outline)

        if args.add_grid:
            try:
                font = ImageFont.truetype(args.grid_font, args.grid_text_size)
            except IOError:
                font_path = get_resource_filename('polar2grid.fonts',
                                                  args.grid_font)
                if not os.path.exists(font_path):
                    raise ValueError(
                        "Font path does not exist: {}".format(font_path))
                font = ImageFont.truetype(font_path, args.grid_text_size)

            outline = args.grid_outline[0] if len(
                args.grid_outline) == 1 else tuple(
                    int(x) for x in args.grid_outline)
            minor_outline = args.grid_minor_outline[0] if len(
                args.grid_minor_outline) == 1 else tuple(
                    int(x) for x in args.grid_minor_outline)
            fill = args.grid_fill[0] if len(args.grid_fill) == 1 else tuple(
                int(x) for x in args.grid_fill)
            cw.add_grid(img,
                        area_def,
                        args.grid_D,
                        args.grid_d,
                        font,
                        fill=fill,
                        outline=outline,
                        minor_outline=minor_outline,
                        lon_placement=args.grid_lon_placement,
                        lat_placement=args.grid_lat_placement)

        img.save(output_filename)
Example #22
0
def embellish(basDir, GSHHS_ROOT, imgStr, ii, dateSnap, timeSnap):
    """
    What does this definition do?
    Embellishes the image with custom graphics

    :param basDir: Base directory path
    :param GSHHS_ROOT: GSHHS installation folder
    :param imgStr: Complete path of the output image data as string
    :param ii: Channel name as string
    :param dateSnap: Date (YYYYMMDD) name as string
    :param timeSnap: Time (HHMM) name as string
    :return: Image with all the decorations..

    References:
    [1]. https://stackoverflow.com/questions/18522295/python-pil-change-greyscale-tif-to-rgb
    """

    import os, sys
    import aggdraw, PIL
    from PIL import Image, ImageFont
    from pydecorate import DecoratorAGG as dag
    from pycoast import ContourWriter
    from satpy.resample import get_area_def

    img = Image.open(imgStr, mode = "r")

    # Convert the image into RGB if it's not
    if ("L" or "A" in img.getbands()):
        rgbimg = Image.new("RGBA", img.size)
        rgbimg.paste(img)
        img = rgbimg
    else:
        print("\n It was already an RGB image, so no need to convert!")
    # end if-confition

    # Add logos
    dc = dag(img)
    # dc.add_logo(basDir + 'logo/NCMRWF.png', height = 75.0)
    dc.add_logo(basDir + 'logo/NCMRWF.png', height = 75.0, bg='yellow')

    # Add basic text information
    capStr = ii
    textStr = "MSG-1: SEVIRI [" + capStr + "]\n" + dateSnap + '\n' + timeSnap + ' UTC'
    # fontClr = aggdraw.Font((255, 255, 255), "/usr/share/fonts/truetype/DejaVuSerif.ttf", size = 18)
    fontClr = aggdraw.Font('blue', "/usr/share/fonts/truetype/DejaVuSerif.ttf", size = 18)
    dc.add_text(textStr, font = fontClr)

    # Adding partner's logos
    dc.align_right()
    dc.add_logo(basDir + 'logo/imdlogo.jpg', height=75.0)
    dc.align_left()
    dc.align_bottom()
    dc.add_logo(basDir + 'logo/eumetsatLogo.jpg', height=50.0)
    dc.align_right()
    dc.add_logo(basDir + 'logo/pytroll-logo.png', height = 50.0)

    # Add coastline, grid to the image
    # Set up projection info for coastlines
    proj4_str = '+proj=merc +lon_0=75.0 + lat_0=17.5 + lat_ts=17.5 +ellps=WGS84'
    area_extent = (-3339584.72, -1111475.10, 3339584.72, 5591295.92)
    area_def = (proj4_str, area_extent)

    # Add the shape file directory or the GSHHS root path
    cw = ContourWriter(GSHHS_ROOT)
    cw.add_coastlines(img, area_def, resolution = 'h', level = 1)
    cw.add_shapefile_shapes(img, area_def, GSHHS_ROOT + 'India/Admin2.shp', outline = 'white')

    # Add gridlines
    fontClr2 = ImageFont.truetype("/usr/share/fonts/truetype/DejaVuSerif.ttf", 14)
    cw.add_grid(img, area_def, (10.0, 10.0), (2.0, 2.0), fontClr2, fill = "white", outline = 'lightblue',
                minor_outline = 'lightblue')

    # Save the image
    img.save(imgStr)

    # return the image object
    return img
Example #23
0
    lcd = scn.resample('euro4', radius_of_influence=2000)

    sstdata = lcd['sea_surface_temperature'][:]
    import numpy as np
    arr = np.ma.where(np.less_equal(sstdata, 0), 0, sstdata - 273.15)

    # Convert sst to numbers between 0 and 28, corresponding to the lut:
    data = np.ma.where(np.less(arr, 0), 28, 28.0 - arr)
    data = np.ma.where(np.greater(arr, 23.0), 4, data).round().astype('uint8')

    from trollimage.image import Image
    from satpy.imageo import palettes
    palette = palettes.sstlut_osisaf_metno()

    img = Image(data, mode='P', palette=palette)
    img.show()
    img.save('osisaf_sst_viirs_satpy.png')

    from pycoast import ContourWriter

    cw_ = ContourWriter('/home/a000680/data/shapes')
    pilim = img.pil_image()
    area_def = lcd['sea_surface_temperature'].info['area']
    cw_.add_coastlines(pilim,
                       area_def,
                       resolution='i',
                       level=1,
                       outline=(220, 220, 220))
    pilim.show()
    pilim.save('./osisaf_sst_viirs_satpy_withovl.png')
Example #24
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):
        LOG.error("Please specify one of the '--add-X' options to modify the image")
        return -1

    for input_tiff, output_filename in zip(args.input_tiff, args.output_filename):
        LOG.info("Creating {} from {}".format(output_filename, input_tiff))
        gtiff = gdal.Open(input_tiff)
        proj4_str = osr.SpatialReference(gtiff.GetProjection()).ExportToProj4()
        ul_x, res_x, _, ul_y, _, res_y = gtiff.GetGeoTransform()
        half_pixel_x = res_x / 2.
        half_pixel_y = res_y / 2.
        area_extent = (
            ul_x - half_pixel_x,  # lower-left X
            ul_y + res_y * gtiff.RasterYSize - half_pixel_y,  # lower-left Y
            ul_x + res_x * gtiff.RasterXSize + half_pixel_x,  # upper-right X
            ul_y + half_pixel_y,  # upper-right Y
        )
        img = Image.open(input_tiff).convert('RGB')
        area_def = (proj4_str, area_extent)

        cw = ContourWriter(args.shapes_dir)

        if args.add_coastlines:
            outline = args.coastlines_outline[0] if len(args.coastlines_outline) == 1 else tuple(int(x) for x in args.coastlines_outline)
            if args.coastlines_fill:
                fill = args.coastlines_fill[0] if len(args.coastlines_fill) == 1 else tuple(int(x) for x in args.coastlines_fill)
            else:
                fill = None
            cw.add_coastlines(img, area_def, resolution=args.coastlines_resolution, level=args.coastlines_level,
                              outline=outline, fill=fill)

        if args.add_rivers:
            outline = args.rivers_outline[0] if len(args.rivers_outline) == 1 else tuple(int(x) for x in args.rivers_outline)
            cw.add_rivers(img, area_def,
                          resolution=args.rivers_resolution, level=args.rivers_level,
                          outline=outline)

        if args.add_borders:
            outline = args.borders_outline[0] if len(args.borders_outline) == 1 else tuple(int(x) for x in args.borders_outline)
            cw.add_borders(img, area_def, resolution=args.borders_resolution, level=args.borders_level, outline=outline)

        if args.add_grid:
            try:
                font = ImageFont.truetype(args.grid_font, args.grid_text_size)
            except IOError:
                font_path = get_resource_filename('polar2grid.fonts', args.grid_font)
                if not os.path.exists(font_path):
                    raise ValueError("Font path does not exist: {}".format(font_path))
                font = ImageFont.truetype(font_path, args.grid_text_size)

            outline = args.grid_outline[0] if len(args.grid_outline) == 1 else tuple(int(x) for x in args.grid_outline)
            minor_outline = args.grid_minor_outline[0] if len(args.grid_minor_outline) == 1 else tuple(int(x) for x in args.grid_minor_outline)
            fill = args.grid_fill[0] if len(args.grid_fill) == 1 else tuple(int(x) for x in args.grid_fill)
            cw.add_grid(img, area_def, args.grid_D, args.grid_d, font,
                        fill=fill, outline=outline, minor_outline=minor_outline,
                        lon_placement=args.grid_lon_placement,
                        lat_placement=args.grid_lat_placement)

        img.save(output_filename)