Exemple #1
0
def add_to_array(arr, area, time, bufr, savedir='/tmp', name=None, mode='L',
                 resize=None, ptsize=None, save=False):
    """Add synoptical reports from stations to provided geolocated image array
    """
    # Create array image
    arrshp = arr.shape[:2]
    print(np.nanmin(arr), np.nanmax(arr))
    arr_img = Image(arr, mode=mode)
    # arr_img = Image(channels=[arr[:, :, 0], arr[:, :, 1], arr[:, :, 2]],
    #                mode='RGB')
    arr_img.stretch('crude')
    arr_img.invert()
    arr_img.colorize(maskcol)
    arr_img.invert()

    # Import bufr
    stations = read_synop(bufr, 'visibility')
    currentstations = stations[time.strftime("%Y%m%d%H0000")]
    lats = [i[2] for i in currentstations]
    lons = [i[3] for i in currentstations]
    vis = [i[4] for i in currentstations]

    # Create array for synop parameter
    visarr = np.empty(arrshp)
    visarr.fill(np.nan)

    x, y = (area.get_xy_from_lonlat(lons, lats))
    vis_ma = np.ma.array(vis, mask=x.mask)
    if ptsize:
        xpt = np.array([])
        ypt = np.array([])
        for i, j in zip(x, y):
            xmesh, ymesh = np.meshgrid(np.linspace(i - ptsize, i + ptsize,
                                                   ptsize * 2 + 1),
                                       np.linspace(j - ptsize, j + ptsize,
                                                   ptsize * 2 + 1))
            xpt = np.append(xpt, xmesh.ravel())
            ypt = np.append(ypt, ymesh.ravel())
        vispt = np.ma.array([np.full(((ptsize * 2 + 1,
                                       ptsize * 2 + 1)), p) for p in vis_ma])
        visarr[ypt.astype(int), xpt.astype(int)] = vispt.ravel()
    else:
        visarr[y.compressed(), x.compressed()] = vis_ma.compressed()
    visarr_ma = np.ma.masked_invalid(visarr)
    station_img = Image(visarr_ma, mode='L')
    station_img.colorize(vis_colset)
    station_img.merge(arr_img)
    if resize is not None:
        station_img.resize((arrshp[0] * resize, arrshp[1] * resize))
    if name is None:
        timestr = time.strftime("%Y%m%d%H%M")
        name = "fog_filter_example_stations_{}.png".format(timestr)
    if save:
        savepath = os.path.join(savedir, name)
        station_img.save(savepath)

    return(station_img)
def plot(data, text, minmax=None, transpose=False, 
         filename=None, position=(-16.743860721,64.915348712,712.4), 
         tilt=None, target_position=None, target_name="", vfov=18.5, tick_distance=50.0):

    if transpose:
        data = data.transpose()

    if minmax is None:
        rainbow.set_range(data.min(),data.max())
    else:
        rainbow.set_range(minmax[0],minmax[1])


    img = Image(data, mode="L")
    img.colorize(rainbow)
    img = img.pil_image()
    
    # Decoration
    dc = DecoratorAGG(img)
    dc.align_bottom()
    #dc.add_logo("/home/sat/dev/pydecorate/logos/VI_Logo_Transp.png")
    #dc.add_logo("Nicarnica-Aviation-22-oct-300x102.png")
    try:
        dc.add_logo("/home/master/bin/futurevolc_logo.png", height=47)
        dc.add_logo("/home/master/bin/nicarnica_logo.png")
        dc.add_logo("/home/master/bin/vi_logo.png")
    except IOError:
        dc.add_logo("bin/futurevolc_logo.png", height=47)
        dc.add_logo("bin/nicarnica_logo.png")
        dc.add_logo("bin/vi_logo.png")

    dc.add_text(text, font=font)
    tick_space = 5.0
    #dc.add_scale(rainbow, extend=True, unit='°C', tick_marks=tick_space, minor_tick_marks=tick_space)

    # target distance and km/px
    ny = data.shape[0]
    nx = data.shape[1]
    distance = distance_longlat(target_position,position)
    
    # plot grid
    lines, texts = prepare_graticule(nx, ny, distance=distance, vfov=vfov, 
                                     tilt=tilt, tick_distance=tick_distance,
                                     height=position[2],target_height=target_position[2],
                                     target_name=target_name)
    draw_lines(img, lines)
    draw_texts(img, texts)

    if filename == None:
        img.show()
    else:
        img.save(filename, "JPEG", quality=90)
Exemple #3
0
    def save(self,
             filename,
             compression=6,
             tags=None,
             gdal_options=None,
             fformat=None,
             blocksize=256,
             **kwargs):
        """Save the image to the given *filename*. If the extension is "tif",
        the image is saved to geotiff_ format, in which case the *compression*
        level can be given ([0, 9], 0 meaning off). See also
        :meth:`image.Image.save`, :meth:`image.Image.double_save`, and
        :meth:`image.Image.secure_save`.  The *tags* argument is a dict of tags
        to include in the image (as metadata), and the *gdal_options* holds
        options for the gdal saving driver. A *blocksize* other than 0 will
        result in a tiled image (if possible), with tiles of size equal to
        *blocksize*.

        If the specified format *fformat* is not know to satpy (and PIL), we
        will try to import module *fformat* and call the method `fformat.save`.


        .. _geotiff: http://trac.osgeo.org/geotiff/
        """
        file_tuple = os.path.splitext(filename)
        fformat = fformat or file_tuple[1][1:]

        if fformat.lower() in ('tif', 'tiff'):
            return self.geotiff_save(filename, compression, tags, gdal_options,
                                     blocksize, **kwargs)
        try:
            # Let image.pil_save it ?
            Image.save(self, filename, compression, fformat=fformat)
        except UnknownImageFormat:
            # No ... last resort, try to import an external module.
            logger.info("Importing image writer module '%s'" % fformat)
            try:
                saver = __import__(fformat, globals(), locals(), ['save'])
            except ImportError:
                raise UnknownImageFormat("Unknown image format '%s'" % fformat)
            saver.save(self, filename, **kwargs)
Exemple #4
0
    def save(self, filename, compression=6,
             tags=None, gdal_options=None,
             fformat=None, blocksize=256, **kwargs):
        """Save the image to the given *filename*. If the extension is "tif",
        the image is saved to geotiff_ format, in which case the *compression*
        level can be given ([0, 9], 0 meaning off). See also
        :meth:`image.Image.save`, :meth:`image.Image.double_save`, and
        :meth:`image.Image.secure_save`.  The *tags* argument is a dict of tags
        to include in the image (as metadata), and the *gdal_options* holds
        options for the gdal saving driver. A *blocksize* other than 0 will
        result in a tiled image (if possible), with tiles of size equal to
        *blocksize*.

        If the specified format *fformat* is not know to MPOP (and PIL), we
        will try to import module *fformat* and call the method `fformat.save`.


        .. _geotiff: http://trac.osgeo.org/geotiff/
        """
        file_tuple = os.path.splitext(filename)
        fformat = fformat or file_tuple[1][1:]

        if fformat.lower() in ('tif', 'tiff'):
            return self.geotiff_save(filename, compression, tags,
                                     gdal_options, blocksize, **kwargs)
        try:
            # Let image.pil_save it ?
            Image.save(self, filename, compression, fformat=fformat)
        except UnknownImageFormat:
            # No ... last resort, try to import an external module.
            logger.info("Importing image writer module '%s'" % fformat)
            try:
                saver = __import__(fformat, globals(), locals(), ['save'])
            except ImportError:
                raise  UnknownImageFormat(
                    "Unknown image format '%s'" % fformat)
            saver.save(self, filename, **kwargs)
Exemple #5
0
    def save(self, filename, compression=6,
             tags=None, gdal_options=None,
             fformat=None, blocksize=256, writer_options=None, **kwargs):
        """Save the image to the given *filename*. If the extension is "tif",
        the image is saved to geotiff_ format, in which case the *compression*
        level can be given ([0, 9], 0 meaning off). See also
        :meth:`image.Image.save`, :meth:`image.Image.double_save`, and
        :meth:`image.Image.secure_save`.  The *tags* argument is a dict of tags
        to include in the image (as metadata), and the *gdal_options* holds
        options for the gdal saving driver. A *blocksize* other than 0 will
        result in a tiled image (if possible), with tiles of size equal to
        *blocksize*.
        If the specified format *fformat* is not know to MPOP (and PIL), we
        will try to import module *fformat* and call the method `fformat.save`.

        Use *writer_options* to define parameters that should be forwarded to
        custom writers. Dictionary keys listed in
        mpop.imageo.formats.writer_options will be interpreted by this
        function instead of *compression*, *blocksize* and nbits in
        *tags* dict.

        .. _geotiff: http://trac.osgeo.org/geotiff/
        """
        fformat = fformat or os.path.splitext(filename)[1][1:]

        # prefer parameters in writer_options dict
        # fill dict if parameters are missing
        writer_options = writer_options or {}
        tags = tags or {}
        if writer_options.get(write_opts.WR_OPT_COMPRESSION, None):
            compression = writer_options[write_opts.WR_OPT_COMPRESSION]
        elif compression is not None:
            writer_options[write_opts.WR_OPT_COMPRESSION] = compression

        if writer_options.get(write_opts.WR_OPT_BLOCKSIZE, None):
            blocksize = writer_options[write_opts.WR_OPT_BLOCKSIZE]
        elif blocksize is not None:
            writer_options[write_opts.WR_OPT_BLOCKSIZE] = blocksize

        if writer_options.get(write_opts.WR_OPT_NBITS, None):
            tags['NBITS'] = writer_options[write_opts.WR_OPT_NBITS]
        elif tags.get('NBITS') is not None:
            writer_options[write_opts.WR_OPT_NBITS] = tags.get('NBITS')

        if fformat.lower() in ('tif', 'tiff'):
            kwargs = kwargs or {}
            kwargs['writer_options'] = writer_options
            return self.geotiff_save(filename, compression, tags,
                                     gdal_options, blocksize,
                                     **kwargs)
        try:
            # Let image.pil_save it ?
            Image.save(self, filename, compression, fformat=fformat)
        except UnknownImageFormat:
            # No ... last resort, try to import an external module.
            logger.info("Importing image writer module '%s'" % fformat)
            try:
                saver = __import__(fformat, globals(), locals(), ['save'])
            except ImportError:
                raise UnknownImageFormat(
                    "Unknown image format '%s'" % fformat)
            kwargs = kwargs or {}
            kwargs['writer_options'] = writer_options
            saver.save(self, filename, **kwargs)
Exemple #6
0
img = Timage(imgarr, mode="L")
#black = greys
#black.colors[0] = np.array([0.,0.,0.])
#black.set_range(-40 + 273.15, 30 + 273.15)
greys.set_range(-30 + 273.15, 30 + 273.15)
#spectral.set_range(-90 + 273.15, -40.00001 + 273.15)
#my_cm = spectral + greys
setvak = cmap_from_text("setvak_rev.rgb", norm=True)
setvak_new = setvak.colors[:,:3]
setvak.colors = setvak_new
setvak.set_range(-73 + 273.15, -30.00001 + 273.15)
my_cm = setvak + greys

img.colorize(my_cm)
tmpFile = "/tmp/colir.png"
img.save(tmpFile)

outputFile = "/var/tmp/cll/out/PY_colir-ch_"+yearS+monthS+dayS+hourS+minS+".png" 

#background = Image.open(bgFile)
foreground = Image.open(tmpFile)
#background = background.convert("RGBA")

#img_enhancer = ImageEnhance.Brightness(foreground)
#imgN = img_enhancer.enhance(1.5)

#foreground.putalpha(imgN.convert('L'))
foreground = foreground.convert("RGBA")
foreground.save(tmpFile)
#Image.alpha_composite(background, foreground).save(outputFile)
print("convert  "+ tmpFile +" \( " +tmpFileB+ " -black-threshold 30% \) -alpha off -comopse copy_opacity -composite " + tmpFile)
Exemple #7
0
def add_to_image(image,
                 area,
                 time,
                 bufr,
                 savedir='/tmp',
                 name=None,
                 bgimg=None,
                 resize=None,
                 ptsize=None,
                 save=False):
    """Add synoptical visibility reports from station data to provided
    geolocated image array
    """
    arrshp = image.shape[:2]
    # Add optional background image
    if bgimg is not None:
        # Get background image
        bg_img = Image(bgimg.squeeze(), mode='L', fill_value=None)
        bg_img.stretch("crude")
        bg_img.convert("RGB")
        #         bg_img.invert()
        image.merge(bg_img)
    # Import bufr
    stations = read_synop(bufr, 'visibility')
    currentstations = stations[time.strftime("%Y%m%d%H0000")]
    lats = [i[2] for i in currentstations]
    lons = [i[3] for i in currentstations]
    vis = [i[4] for i in currentstations]

    # Create array for synop parameter
    visarr = np.empty(arrshp)
    visarr.fill(np.nan)
    # Red - Violet - Blue - Green
    vis_colset = Colormap((0, (228 / 255.0, 26 / 255.0, 28 / 255.0)),
                          (1000, (152 / 255.0, 78 / 255.0, 163 / 255.0)),
                          (5000, (55 / 255.0, 126 / 255.0, 184 / 255.0)),
                          (10000, (77 / 255.0, 175 / 255.0, 74 / 255.0)))
    x, y = (area.get_xy_from_lonlat(lons, lats))
    vis_ma = np.ma.array(vis, mask=x.mask)
    if ptsize:
        xpt = np.array([])
        ypt = np.array([])
        for i, j in zip(x, y):
            xmesh, ymesh = np.meshgrid(
                np.linspace(i - ptsize, i + ptsize, ptsize * 2 + 1),
                np.linspace(j - ptsize, j + ptsize, ptsize * 2 + 1))
            xpt = np.append(xpt, xmesh.ravel())
            ypt = np.append(ypt, ymesh.ravel())
        vispt = np.ma.array(
            [np.full(((ptsize * 2 + 1, ptsize * 2 + 1)), p) for p in vis_ma])
        visarr[ypt.astype(int), xpt.astype(int)] = vispt.ravel()
    else:
        visarr[y.compressed(), x.compressed()] = vis_ma.compressed()
    visarr_ma = np.ma.masked_invalid(visarr)
    station_img = Image(visarr_ma, mode='L')
    station_img.colorize(vis_colset)
    image.convert("RGB")
    station_img.merge(image)
    if resize is not None:
        station_img.resize((arrshp[0] * resize, arrshp[1] * resize))
    if name is None:
        timestr = time.strftime("%Y%m%d%H%M")
        name = "fog_filter_example_stations_{}.png".format(timestr)
    if save:
        savepath = os.path.join(savedir, name)
        station_img.save(savepath)

    return (station_img)
        if save_black_white_png:
            local_scene.save_dataset('lscl', './lscl_' + area + '.png')
            print(dir(local_scene.save_dataset))
            print('display ./lscl_' + area + '.png &')

        # save png file for SATLive
        ##############################
        if area == "cosmo1x150" or area == "cosmo1":
            png_file = start_time.strftime('/data/cinesat/out/MSG_lscl-' +
                                           area + '_%y%m%d%H%M.png')
            from trollimage.colormap import spectral, greys, ylorrd, rdgy
            imgarr = np.array(local_scene['lscl'].data)
            from trollimage.image import Image as Timage
            img = Timage(imgarr, mode="L")
            img.colorize(rdgy.reverse())
            img.save(png_file)

            # local_scene.save_dataset( 'lscl', png_file )
            from pyresample.utils import load_area
            swiss = load_area("/opt/users/hau/monti-pytroll/etc/areas.def",
                              area)

            from pycoast import ContourWriterAGG
            cw = ContourWriterAGG('/opt/users/common/shapes')
            cw.add_borders_to_file(png_file,
                                   swiss,
                                   outline="green",
                                   resolution='i',
                                   level=3,
                                   width=2)
Exemple #9
0
    #print(np.histogram(cwp_masked.compressed()))
    #ele_img.show()
    #cwp_img.show()
    #overview.show()
    #fls_img.show()
    #snow_rgb.show()
    #daymicro_rgb.show()
    ele_img.save("/tmp/fog_example_msg_ger_elevation_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    cot_img.save("/tmp/fog_example_msg_ger_cot_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    reff_img.save("/tmp/fog_example_msg_ger_reff_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    cwp_img.save("/tmp/fog_example_msg_ger_cwp_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    fls_img.save("/tmp/fog_example_msg_ger_fls_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    overview.save("/tmp/fog_example_msg_ger_overview_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    snow_rgb.save("/tmp/fog_example_msg_ger_snow_rgb_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    daymicro_rgb.save("/tmp/fog_example_msg_ger_daymicro_rgb_{}.png".format(
        time.strftime("%Y%m%d%H%M")))
    #germ_scene["HRV"].show()

    # Add synoptical mreports from stations
    arrshp = germ_scene[10.8].shape
    bufr_dir = '/data/tleppelt/skydata/'
    bufr_file = "result_{}".format(time.strftime("%Y%m%d"))

    inbufr = os.path.join(bufr_dir, bufr_file)
    stations = read_synop(inbufr, 'visibility')
Exemple #10
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')
Exemple #11
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')