Example #1
0
    def _init(self):
        """Initialize from a tradition segment data or from an
           existing colormap redefining the intrinsic alpha channel.
        """

        #       Inherit segment data from an existing colormap,
        #       possibly redefining alpha channel
        if self._segmentdata.has_key('cmap'):
            if self._segmentdata.has_key('alpha'):
                alphad = self._segmentdata['alpha']  # save this
            else:
                alphad = None
            cmap = self._segmentdata['cmap']
            if not cmap._isinit: cmap._init()
            self._segmentdata = cmap._segmentdata.copy()
            if alphad != None:
                self._segmentdata['alpha'] = alphad  # revised alpha

#       Scale the segment data if requested
#       -----------------------------------
        if self._scale != None:
            scale = lambda x: min(max(self._scale(x), 0.0), 1.0)
            data_s = {}
            for key, val in self._segmentdata.iteritems():
                valnew = [(scale(a), b, c) for a, b, c in val]
                data_s[key] = valnew
            self._segmentdata = data_s

#       Reverse the segment data if requested
#       -------------------------------------
        if self._reverse:
            data_r = {}
            for key, val in self._segmentdata.iteritems():
                valnew = [(1.0 - a, b, c) for a, b, c in reversed(val)]
                data_r[key] = valnew
            self._segmentdata = data_r

#       Go for the LUT
#       --------------
        self._lut = npy.ones((self.N + 3, 4), npy.float)
        self._lut[:-3, 0] = makeMappingArray(self.N, self._segmentdata['red'])
        self._lut[:-3, 1] = makeMappingArray(self.N,
                                             self._segmentdata['green'])
        self._lut[:-3, 2] = makeMappingArray(self.N, self._segmentdata['blue'])

        #       RGB is always there by alpha may not, so we check for it
        #       --------------------------------------------------------
        if self._segmentdata.has_key('alpha'):
            self._lut[:-3, 3] = makeMappingArray(self.N,
                                                 self._segmentdata['alpha'])

#       Save intrinsic alpha
#       --------------------
        self._alpha = self._lut[:-3, 3][:]

        self._isinit = True
        self._set_extremes()
Example #2
0
 def _custom_listed_color_map(self, name, N, firstBlack=False):
     """ add the black color in front of 'name' color """
     import matplotlib.cm as cm
     from matplotlib import colors
     mp = cm.datad[name]
     new_mp1 = {'blue': colors.makeMappingArray(N-1, mp['blue']),
               'green': colors.makeMappingArray(N-1, mp['green']),
               'red': colors.makeMappingArray(N-1, mp['red'])}
     new_mp2 = []
     new_mp2.extend(zip(new_mp1['red'], new_mp1['green'], new_mp1['blue']))
     if firstBlack == True:
         new_mp2 = [(0,0,0)]+new_mp2 # the black color
     return colors.ListedColormap(new_mp2, N=N-1), new_mp2
Example #3
0
 def _custom_listed_color_map(self, name, N, firstBlack=False):
     """ add the black color in front of 'name' color """
     import matplotlib.cm as cm
     from matplotlib import colors
     mp = cm.datad[name]
     new_mp1 = {
         'blue': colors.makeMappingArray(N - 1, mp['blue']),
         'green': colors.makeMappingArray(N - 1, mp['green']),
         'red': colors.makeMappingArray(N - 1, mp['red'])
     }
     new_mp2 = []
     new_mp2.extend(zip(new_mp1['red'], new_mp1['green'], new_mp1['blue']))
     if firstBlack == True:
         new_mp2 = [(0, 0, 0)] + new_mp2  # the black color
     return colors.ListedColormap(new_mp2, N=N - 1), new_mp2
Example #4
0
def gen_gradient_mask(size,
                      palette,
                      icon_dir='.temp',
                      gradient_dir='horizontal'):
    """Generates a gradient color mask from a specified palette."""
    mask_array = gen_mask_array(icon_dir, 'float32')

    palette_func = gen_palette(palette)
    gradient = np.array(makeMappingArray(size, palette_func.mpl_colormap))

    # matplotlib color maps are from range of (0, 1). Convert to RGB.
    gradient *= 255.

    # Add new axis and repeat gradient across it.
    gradient = np.tile(gradient, (size, 1, 1))

    # if vertical, transpose the gradient.
    if gradient_dir == 'vertical':
        gradient = np.transpose(gradient, (1, 0, 2))

    # Turn any nonwhite pixels on the icon into the gradient colors.
    white = (255., 255., 255., 255.)
    mask_array[mask_array != white] = gradient[mask_array != white]

    image_colors = ImageColorGenerator(mask_array)
    return image_colors, np.uint8(mask_array)
Example #5
0
def plot_colourbar(clr_ax, cmap, data=None, mima=False, plusminus=False, zorder=1):
    """
    Puts a colorbar under / behind histogram
    """
    seisbar = cm.get_cmap(cmap)
    ncolours = 32
    seis_array = makeMappingArray(ncolours, seisbar)
    color_arr = seis_array[np.newaxis, :]
    color_arr = color_arr[:, :, :-1]
    colour_roll = np.rollaxis(color_arr, 1)
    colour_roll2 = np.rollaxis(colour_roll, 1)
    clr_ax.imshow(colour_roll2, extent=[0, ncolours, 0, 1], aspect='auto', zorder=zorder)
    clr_ax.set_yticks([])
    clr_ax.set_xticks([])
    ma, mi = np.amax(data), np.amin(data)
    if mima:
        clr_ax.text(0.95, 0.5, '{:3.0f}'.format(mi),
                    transform=clr_ax.transAxes,
                    horizontalalignment='center', verticalalignment='top',
                    fontsize=8)
        clr_ax.text(0.05, 0.5, '{:3.0f}'.format(ma), transform=clr_ax.transAxes,
                    horizontalalignment='center',
                    fontsize=8)
    if plusminus:
        clr_ax.text(0.95, 0.5, "+",
                    transform=clr_ax.transAxes,
                    ha='right', color='w',
                    va='center', fontsize=16)
        clr_ax.text(0.05, 0.5, "-",
                    transform=clr_ax.transAxes, color='k',
                    ha='left', va='center', fontsize=16)

    return clr_ax
Example #6
0
def plot_colourbar(clr_ax,
                   cmap,
                   data=None,
                   mima=False,
                   plusminus=False,
                   zorder=1):
    """
    Puts a colorbar under / behind histogram
    """
    seisbar = cm.get_cmap(cmap)
    ncolours = 32
    seis_array = makeMappingArray(ncolours, seisbar)
    color_arr = seis_array[np.newaxis, :]
    color_arr = color_arr[:, :, :-1]
    colour_roll = np.rollaxis(color_arr, 1)
    colour_roll2 = np.rollaxis(colour_roll, 1)
    clr_ax.imshow(colour_roll2,
                  extent=[0, ncolours, 0, 1],
                  aspect='auto',
                  zorder=zorder)
    clr_ax.set_yticks([])
    clr_ax.set_xticks([])
    ma, mi = np.amax(data), np.amin(data)
    if mima:
        clr_ax.text(0.95,
                    0.5,
                    '{:3.0f}'.format(mi),
                    transform=clr_ax.transAxes,
                    horizontalalignment='center',
                    verticalalignment='top',
                    fontsize=8)
        clr_ax.text(0.05,
                    0.5,
                    '{:3.0f}'.format(ma),
                    transform=clr_ax.transAxes,
                    horizontalalignment='center',
                    fontsize=8)
    if plusminus:
        clr_ax.text(0.95,
                    0.5,
                    "+",
                    transform=clr_ax.transAxes,
                    ha='right',
                    color='w',
                    va='center',
                    fontsize=16)
        clr_ax.text(0.05,
                    0.5,
                    "-",
                    transform=clr_ax.transAxes,
                    color='k',
                    ha='left',
                    va='center',
                    fontsize=16)

    return clr_ax
Example #7
0
def make_gradient(img_size, palette_name):
    background = Image.new('RGBA', img_size, (0, 0, 0, 0))
    palette = makeMappingArray(img_size[0], get_cmap(palette_name))

    rgb_sequence = []
    for x in range(img_size[0]):
        color = palette[x]

        # matplotlib color maps are from range of (0,1). Convert to RGB.
        r = int(color[0] * 255)
        g = int(color[1] * 255)
        b = int(color[2] * 255)

        rgb_sequence.append((r, g, b))

    background.putdata(rgb_sequence * img_size[1])

    return background
Example #8
0
icon = "flag"
gradient_orientation = "h"

# http://stackoverflow.com/questions/7911451/pil-convert-png-or-gif-with-transparency-to-jpg-without
icon_path = fa_path + "%s.png" % icon
icon = Image.open(icon_path)
mask = Image.new("RGB", icon.size, (255,255,255))
mask.paste(icon,icon)
mask_wordcloud = np.array(mask)

# Create a linear gradient using the matplotlib color map

imgsize = icon.size

palette = makeMappingArray(imgsize[1], Spectral_9.mpl_colormap)   # interpolates colors

for y in range(imgsize[1]):
    for x in range(imgsize[0]):
    	if mask.getpixel((x,y)) != (255,255,255):   # Only change nonwhite pixels of icon
    	
    		color = palette[y] if gradient_orientation is "vertical" else palette[x]
    		
    		# matplotlib color maps are from range of (0,1). Convert to RGB.
    		r = int(color[0] * 255)
    		g = int(color[1] * 255)
    		b = int(color[2] * 255)
    		
    		mask.putpixel((x, y), (r, g, b))
			
# create coloring from image
Example #9
0
       [248, 223,   0],
       [249, 226,   0],
       [249, 228,   0],
       [250, 230,   0],
       [250, 232,   0],
       [251, 235,   0],
       [251, 237,   0],
       [252, 239,   0],
       [252, 242,   0],
       [253, 244,   0],
       [253, 246,   0],
       [254, 249,   0],
       [254, 251,   0],
       [255, 253,   0],
       [255, 255,   0]], dtype='uint8')


myCmaps ={'hot': _cetHot_dat,
          'Blue-Black-Yellow': _cetBlueBlackYellow_dat,
          'Blue-Black-Red': _cetBlueBlackRed_dat,
          'rainbow': _cetRainbowDivering_dat,
          'temperature': _temp_dat,
          'Blue-Green-Yellow-Red': _bgylrd_dat}

keys = ['viridis', 'magma', 'inferno', 'plasma', 'gnuplot', 'gnuplot2', 'coolwarm', 'PuOr', 'RdYlGn', 'PiYG', 'PRGn', 'RdBu', 'winter']
for k in keys:
    myCmaps[k] = np.array(makeMappingArray(256,get_cmap(k))[:,0:3]*255, dtype = 'uint8')
myCmaps['Spectral'] = np.array(makeMappingArray(256,get_cmap('Spectral_r'))[:,0:3]*255, dtype = 'uint8')
myCmaps['BuYlRd'] = np.array(makeMappingArray(256,get_cmap('RdYlBu_r'))[:,0:3]*255, dtype = 'uint8')
myCmaps_names = [key for key in myCmaps.keys()]
Example #10
0
from matplotlib import cm
from matplotlib.colors import makeMappingArray, rgb_to_hsv, hsv_to_rgb
import numpy as np
import matplotlib.pyplot as plt

seisbar = cm.get_cmap('RdBu')

ncolours = 256
seis_array = makeMappingArray(ncolours, seisbar)
np.shape(seis_array)

color_arr = seis_array[np.newaxis, :]
color_arr = color_arr[:, :, :-1]

colour_roll = np.rollaxis(color_arr, 1)
seis_rgb_mtx = np.tile(colour_roll, (256, 1))
np.shape(seis_rgb_mtx)

seis_hsv = rgb_to_hsv(seis_rgb_mtx)
hues, lightness = np.mgrid[0:1:256j, 0:1.0:256j]
seis_hsv[:, :, 2] *= lightness

RGB = hsv_to_rgb(seis_hsv)

fig = plt.figure(figsize=(4, 5))
ax = fig.add_subplot(111, axisbg='k')
ax.imshow(RGB, origin="lower", extent=[0, 1, 0, 1])

plt.show()
Example #11
0
    def set_image(self,
                  image,
                  row,
                  col,
                  cmap=None,
                  vmin=None,
                  vmax=None,
                  vsym=False):
        """
        Sets the data for a single window.

        Parameters
        ----------
        image : ndarray, ndim=2
            The shape should be the same as the `shape` specified when
            constructing the image grid.
        row, col : int
            The zero-index of the row and column to set.
        cmap : cmap (from matplotlib.pylab.cm)
            The color palette to use. Default is grayscale.
        vmin, vmax : numerical or None
            Defines the range of the color palette. None, which is default,
            takes the range of the data.
        vsym : bool
            If True, this means that the color palette will always be centered
            around 0. Even if you have specified both `vmin` and `vmax`, this
            will override that and extend the shorter one. Good practice is to
            specify neither `vmin` or `vmax` or only `vmax` together with this
            option.
        """
        from matplotlib import colors
        from matplotlib.pylab import cm
        from deepdish.plot.resample import resample_and_arrange_image

        if cmap is None:
            cmap = cm.gray
        if vmin is None:
            vmin = np.nanmin(image)
        if vmax is None:
            vmax = np.nanmax(image)

        if vsym and -vmin != vmax:
            mx = max(abs(vmin), abs(vmax))
            vmin = -mx
            vmax = mx

        if vmin == vmax:
            diff = 1
        else:
            diff = vmax - vmin

        image_indices = np.clip((image - vmin) / diff, 0, 1) * 255
        image_indices = image_indices.astype(np.uint8)

        nan_mask = np.isnan(image).astype(np.uint8)

        lut = colors.makeMappingArray(256, cmap)
        rgb = resample_and_arrange_image(image_indices, nan_mask, self._shape,
                                         lut)

        x0 = row * (self._shape[0] + self._border)
        x1 = (row + 1) * (self._shape[0] + self._border) + self._border
        y0 = col * (self._shape[1] + self._border)
        y1 = (col + 1) * (self._shape[1] + self._border) + self._border

        self._data[x0:x1, y0:y1] = self._border_color

        anchor = (self._border + row * (self._shape[0] + self._border),
                  self._border + col * (self._shape[1] + self._border))

        selection = [
            slice(anchor[0], anchor[0] + rgb.shape[0]),
            slice(anchor[1], anchor[1] + rgb.shape[1])
        ]

        nan_data = np.isnan(rgb)
        rgb[nan_data] = 0.0

        self._data[selection] = (rgb * ~nan_data +
                                 self._border_color * nan_data)
Example #12
0
    def set_image(self, image, row, col, cmap=None, vmin=None, vmax=None,
                  vsym=False):
        """
        Sets the data for a single window.

        Parameters
        ----------
        image : ndarray, ndim=2
            The shape should be the same as the `shape` specified when
            constructing the image grid.
        row/col : int
            The zero-index of the row and column to set.
        cmap : cmap (from matplotlib.pylab.cm)
            The color palette to use. Default is grayscale.
        vmin/vmax : numerical or None
            Defines the range of the color palette. None, which is default,
            takes the range of the data.
        vsym : bool
            If True, this means that the color palette will always be centered
            around 0. Even if you have specified both `vmin` and `vmax`, this
            will override that and extend the shorter one. Good practice is to
            specify neither `vmin` or `vmax` or only `vmax` together with this
            option.
        """
        from matplotlib import colors
        from matplotlib.pylab import cm
        from vzlog.image.resample import resample_and_arrange_image

        if cmap is None:
            if vsym:
                # Pick a default that is white exactly at 0
                cmap = cm.RdBu_r
            else:
                cmap = cm.gray
        if vmin is None:
            vmin = np.nanmin(image)
        if vmax is None:
            vmax = np.nanmax(image)

        if vsym and -vmin != vmax:
            mx = max(abs(vmin), abs(vmax))
            vmin = -mx
            vmax = mx

        if vmin == vmax:
            diff = 1
        else:
            diff = vmax - vmin

        image_indices = np.clip((image - vmin) / diff, 0, 1) * 255
        image_indices = image_indices.astype(np.uint8)

        nan_mask = np.isnan(image).astype(np.uint8)

        lut = colors.makeMappingArray(256, cmap)
        rgb = resample_and_arrange_image(image_indices, nan_mask, self._shape,
                                         lut)

        x0 = row * (self._shape[0] + self._border)
        x1 = (row + 1) * (self._shape[0] + self._border) + self._border
        y0 = col * (self._shape[1] + self._border)
        y1 = (col + 1) * (self._shape[1] + self._border) + self._border

        self._data[x0:x1, y0:y1] = self._border_color

        anchor = (self._border + row * (self._shape[0] + self._border),
                  self._border + col * (self._shape[1] + self._border))

        selection = [slice(anchor[0], anchor[0] + rgb.shape[0]),
                     slice(anchor[1], anchor[1] + rgb.shape[1])]

        nan_data = np.isnan(rgb)
        rgb[nan_data] = 0.0

        self._data[selection] = (rgb * ~nan_data +
                                 self._border_color * nan_data)
Example #13
0
def test_makeMappingArray(N, result):
    data = [(0.0, 1.0, 1.0), (0.5, 0.2, 0.2), (1.0, 0.0, 0.0)]
    assert_array_almost_equal(mcolors.makeMappingArray(N, data), result)