Read ColorMap data from file and return as numpy array.
770840
def read_colormap(fh, byteorder, dtype, count, offsetsize):
    """"""
    cmap = fh.read_array(byteorder+dtype[-1], count)
    cmap.shape = (3, -1)
    return cmap
667336
def _rgbtomask(self, obj):
        """"""
        dat = obj.get_image().get_data()  # RGB arrays
        return dat.sum(axis=2).astype(np.bool)
761323
def array(self, size_chunk, start, bytesize):
        ''' 
        '''

        with open(self.img, 'rb') as f1:
            f1.seek(self.start_byte + start * self.bytesize)
            data = f1.read(size_chunk * self.bytesize)
            Z = np.fromstring(data, dtype=self.dtype, count=size_chunk)
            if self.grid == 'LOLA':
                return Z * float(self.SCALING_FACTOR)
            else:
                return Z
697953
function getColormap() {
    var map = [];
    var index = [];

    for (var i = 0; i < netsize; i++)
      index[network[i][3]] = i;

    var k = 0;
    for (var l = 0; l < netsize; l++) {
      var j = index[l];
      map[k++] = (network[j][0]);
      map[k++] = (network[j][1]);
      map[k++] = (network[j][2]);
    }
    return map;
  }
1210667
def colored_map(text, cmap):
    
    if not __ISON: return text
    for key, v in cmap.items():
        if isinstance(v, dict):
            text = text.replace(key, colored(key, **v))
        else:
            text = text.replace(key, colored(key, color=v))
    return text
1183319
def imread(img, color=None, dtype=None):
    '''
    
    '''
    COLOR2CV = {'gray': cv2.IMREAD_GRAYSCALE,
                'all': cv2.IMREAD_COLOR,
                None: cv2.IMREAD_ANYCOLOR
                }
    c = COLOR2CV[color]
    if callable(img):
        img = img()
    elif isinstance(img, string_types):
        #         from_file = True
        #         try:
        #             ftype = img[img.find('.'):]
        #             img = READERS[ftype](img)[0]
        #         except KeyError:
        # open with openCV
        # grey - 8 bit
        if dtype in (None, "noUint") or np.dtype(dtype) != np.uint8:
            c |= cv2.IMREAD_ANYDEPTH
        img2 = cv2.imread(img, c)
        if img2 is None:
            raise IOError("image '%s' is not existing" % img)
        img = img2

    elif color == 'gray' and img.ndim == 3:  # multi channel img like rgb
        # cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #cannot handle float64
        img = toGray(img)
    # transform array to uint8 array due to openCV restriction
    if dtype is not None:
        if isinstance(img, np.ndarray):
            img = _changeArrayDType(img, dtype, cutHigh=False)

    return img
257916
def _read_color_images(self, num_images):
        
        color_images = self._ros_read_images(self._color_image_buffer, num_images, self.staleness_limit)
        for i in range(0, num_images):
            if self._flip_images:
                color_images[i] = np.flipud(color_images[i].astype(np.uint8))
                color_images[i] = np.fliplr(color_images[i].astype(np.uint8))
            color_images[i] = ColorImage(color_images[i], frame=self._frame) 
        return color_images
762924
def get_map_matrix(inputfile):
    
    matrix = read_input_file(inputfile)
    output = []
    for row in matrix:
        if row[3]:
            output.append([row[3], row[1], row[2]])
    return output
387202
def colorize(self, colormap):
        

        if self.mode not in ("L", "LA"):
            raise ValueError("Image should be grayscale to colorize")

        if self.mode == "LA":
            alpha = self.data.sel(bands=['A'])
        else:
            alpha = None

        l_data = self.data.sel(bands=['L'])

        def _colorize(l_data, colormap):
            # 'l_data' is (1, rows, cols)
            # 'channels' will be a list of 3 (RGB) or 4 (RGBA) arrays
            channels = colormap.colorize(l_data)
            return np.concatenate(channels, axis=0)

        new_data = l_data.data.map_blocks(_colorize, colormap,
                                          chunks=(colormap.colors.shape[1],) + l_data.data.chunks[1:],
                                          dtype=np.float64)

        if colormap.colors.shape[1] == 4:
            mode = "RGBA"
        elif alpha is not None:
            new_data = da.concatenate([new_data, alpha.data], axis=0)
            mode = "RGBA"
        else:
            mode = "RGB"

        # copy the coordinates so we don't affect the original
        coords = dict(self.data.coords)
        coords['bands'] = list(mode)
        attrs = self.data.attrs
        dims = self.data.dims
        self.data = xr.DataArray(new_data, coords=coords, attrs=attrs, dims=dims)
1263000
def build_colormap(palette, dtype, info):
        """"""
        from trollimage.colormap import Colormap
        sqpalette = np.asanyarray(palette).squeeze() / 255.0
        if hasattr(palette, 'attrs') and 'palette_meanings' in palette.attrs:
            meanings = palette.attrs['palette_meanings']
            iterator = zip(meanings, sqpalette)
        else:
            iterator = enumerate(sqpalette[:-1])

        if dtype == np.dtype('uint8'):
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

        elif 'valid_range' in info:
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

            sf = info.get('scale_factor', np.array(1))
            colormap.set_range(
                *info['valid_range'] * sf + info.get('add_offset', 0))

        return colormap, sqpalette
1155967
def read(filename, data_wrapper=DataWrapper):
    ''''''
    data = np.loadtxt(filename)
    if len(np.shape(data)) == 1:
        data = np.reshape(data, (1, -1))
    data = data[:, [X, Y, Z, R, TYPE, ID, P]]
    return data_wrapper(data, 'SWC', None)
1193393
def colorbar(height, length, colormap):
    
    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
    cbar = (cbar * (colormap.values.max() - colormap.values.min())
            + colormap.values.min())

    return colormap.colorize(cbar)
1286573
def read_texture(filename, attrs=None):
    """"""
    filename = os.path.abspath(os.path.expanduser(filename))
    try:
        # intitialize the reader using the extnesion to find it
        reader = get_reader(filename)
        image = standard_reader_routine(reader, filename, attrs=attrs)
        return vtki.image_to_texture(image)
    except KeyError:
        # Otherwise, use the imageio reader
        pass
    return vtki.numpy_to_texture(imageio.imread(filename))
30811
def _get_cmap(kwargs: dict) -> colors.Colormap:
    
    from matplotlib.colors import ListedColormap

    cmap = kwargs.pop("cmap", default_cmap)
    if isinstance(cmap, list):
        return ListedColormap(cmap)
    if isinstance(cmap, str):
        try:
            cmap = plt.get_cmap(cmap)
        except BaseException as exc:
            try:
                # Try to use seaborn palette
                import seaborn as sns
                sns_palette = sns.color_palette(cmap, n_colors=256)
                cmap = ListedColormap(sns_palette, name=cmap)
            except ImportError:
                raise exc
    return cmap
727818
def from_array(cls, array, filename=None, channels=3, scale_to_range=False,
                   grayscale=False, channel_bitdepth=8,
                   has_alpha=False, palette=None):
        
        if scale_to_range:
            amax = array.max()
            amin = array.min()
            _array = (2**channel_bitdepth - 1) * (array - amin) / (amax - amin)
        else:
            _array = array
        _array = numpy.rint(_array).astype(dtype=PNGWriter.get_dtype(channel_bitdepth))  # proper rounding
        return cls(_array, filename, channels=channels,
                   grayscale=grayscale, channel_bitdepth=channel_bitdepth,
                   has_alpha=has_alpha, palette=palette)
1358076
def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2):
    

    reader = pyfits.open(infile)

    distance_modulus_array = reader['DISTANCE_MODULUS'].data.field('DISTANCE_MODULUS')
    if not numpy.any(numpy.fabs(distance_modulus_array - distance_modulus) < 1.e-3):
        logger.warning("Distance modulus %.2f not available in file %s"%(distance_modulus, infile))
        logger.warning('         available distance moduli:'+str(distance_modulus_array))
        return False

    distance_modulus_key = '%.2f'%(distance_modulus_array[numpy.argmin(numpy.fabs(distance_modulus_array - distance_modulus))])

    bins_mag_err = reader['BINS_MAG_ERR'].data.field('BINS_MAG_ERR') 
    bins_mag_1 = reader['BINS_MAG_1'].data.field('BINS_MAG_1') 
    bins_mag_2 = reader['BINS_MAG_2'].data.field('BINS_MAG_2') 
    # Note that magnitude uncertainty is always assigned by rounding up, is this the right thing to do?
    index_mag_err_1 = numpy.clip(numpy.digitize(mag_err_1, bins_mag_err) - 1,
                                 0, len(bins_mag_err) - 2)
    index_mag_err_2 = numpy.clip(numpy.digitize(mag_err_2, bins_mag_err) - 1,
                                 0, len(bins_mag_err) - 2)

    u_color = numpy.zeros(len(mag_1))

    for index_mag_err_1_select in range(0, len(bins_mag_err) - 1):
        for index_mag_err_2_select in range(0, len(bins_mag_err) - 1):
            cut = numpy.logical_and(index_mag_err_1 == index_mag_err_1_select,
                                    index_mag_err_2 == index_mag_err_2_select)
            if numpy.sum(cut) < 1:
                continue
            histo = reader[distance_modulus_key].data.field('%i%i'%(index_mag_err_1_select, index_mag_err_2_select))
            u_color[cut] = ugali.utils.binning.take2D(histo,
                                                      mag_2[cut], mag_1[cut],
                                                      bins_mag_2, bins_mag_1)
    
    reader.close()
    return u_color
498923
def generate_vector_color_map(self):
        """"""
        vector_stops = []

        # if join data specified as filename or URL, parse JSON to list of Python dicts
        if type(self.data) == str:
            self.data = geojson_to_dict_list(self.data)

        # loop through features in self.data to create join-data map
        for row in self.data:
            
            # map color to JSON feature using color_property
            color = color_map(row[self.color_property], self.color_stops, self.color_default)

            # link to vector feature using data_join_property (from JSON object)
            vector_stops.append([row[self.data_join_property], color])

        return vector_stops