Convert PIL mode to ColorMode.
198651
def get_color_mode(mode):
    """"""
    name = mode.upper()
    name = name.rstrip('A')  # Trim alpha.
    name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name)
    return getattr(ColorMode, name)
970838
def do_quality(self, quality):
        
        if (quality == 'grey' or quality == 'gray'):
            # Checking for 1.1 gray or 20.0 grey elsewhere
            self.logger.debug("quality: converting to gray")
            self.image = self.image.convert('L')
        elif (quality == 'bitonal'):
            self.logger.debug("quality: converting to bitonal")
            self.image = self.image.convert('1')
        else:  # color or default/native (which we take as color)
            # Deal first with conversions from I;16* formats which Pillow
            # appears not to handle properly, resulting in mostly white images
            # if we convert directly. See:
            # <http://stackoverflow.com/questions/7247371/python-and-16-bit-tiff>
            if (self.image.mode.startswith('I;16')):
                self.logger.debug("quality: fudged conversion from mode %s to I"
                                  % (self.image.mode))
                self.image = self.image.convert('I')
                self.image = self.image.point(lambda i: i * (1.0 / 256.0))
            if (self.image.mode not in ('1', 'L', 'RGB', 'RGBA')):
                # Need to convert from palette etc. in order to write out
                self.logger.debug("quality: converting from mode %s to RGB"
                                  % (self.image.mode))
                self.image = self.image.convert('RGB')
            else:
                self.logger.debug("quality: quality (nop)")
309248
private void readTrueColor(ImageReadParam pParam, final ImageInputStream pInput) throws IOException {
        final int width = header.width;
        final int height = header.height;

        final Rectangle aoi = getSourceRegion(pParam, width, height);
        final Point offset = pParam == null ? new Point(0, 0) : pParam.getDestinationOffset();

        // Set everything to default values
        int sourceXSubsampling = 1;
        int sourceYSubsampling = 1;
        int[] sourceBands = null;
        int[] destinationBands = null;

        // Get values from the ImageReadParam, if any
        if (pParam != null) {
            sourceXSubsampling = pParam.getSourceXSubsampling();
            sourceYSubsampling = pParam.getSourceYSubsampling();

            sourceBands = pParam.getSourceBands();
            destinationBands = pParam.getDestinationBands();
        }

        // Ensure band settings from param are compatible with images
        checkReadParamBandSettings(pParam, header.bitplanes / 8, image.getSampleModel().getNumBands());

        // NOTE:  Each row of the image is stored in an integral number of 16 bit words.
        // The number of words per row is words=((w+15)/16)
        int planeWidth = 2 * ((width + 15) / 16);
        final byte[] planeData = new byte[8 * planeWidth];

        WritableRaster destination = image.getRaster();
        if (destinationBands != null || offset.x != 0 || offset.y != 0) {
            destination = destination.createWritableChild(0, 0, destination.getWidth(), destination.getHeight(), offset.x, offset.y, destinationBands);
        }
//        WritableRaster raster = image.getRaster().createCompatibleWritableRaster(width, 1);
        WritableRaster raster = image.getRaster().createCompatibleWritableRaster(8 * planeWidth, 1);
        Raster sourceRow = raster.createChild(aoi.x, 0, aoi.width, 1, 0, 0, sourceBands);

        final byte[] data = ((DataBufferByte) raster.getDataBuffer()).getData();
        final int channels = (header.bitplanes + 7) / 8;
        final int planesPerChannel = 8;
        Object dataElements = null;

        for (int srcY = 0; srcY < height; srcY++) {
            for (int c = 0; c < channels; c++) {
                for (int p = 0; p < planesPerChannel; p++) {
                    readPlaneData(pInput, planeData, p * planeWidth, planeWidth);
                }

                // Skip rows outside AOI
                if (srcY >= (aoi.y + aoi.height)) {
                    return;
                }
                else if (srcY < aoi.y || (srcY - aoi.y) % sourceYSubsampling != 0) {
                    continue;
                }

                if (formType == IFF.TYPE_ILBM) {
                    // NOTE: Using (channels - c - 1) instead of just c,
                    // effectively reverses the channel order from RGBA to ABGR
                    int off = (channels - c - 1);

                    int pixelPos = 0;
                    for (int planePos = 0; planePos < planeWidth; planePos++) {
                        IFFUtil.bitRotateCW(planeData, planePos, planeWidth, data, off + pixelPos * channels, channels);
                        pixelPos += 8;
                    }
                }
                else if (formType == IFF.TYPE_PBM) {
                    System.arraycopy(planeData, 0, data, srcY * 8 * planeWidth, planeWidth);
                }
                else {
                    throw new AssertionError(String.format("Unsupported FORM type: %s", formType));
                }
            }

            if (srcY >= aoi.y && (srcY - aoi.y) % sourceYSubsampling == 0) {
                int dstY = (srcY - aoi.y) / sourceYSubsampling;
                // TODO: Support conversion to INT (A)RGB rasters (maybe using ColorConvertOp?)
                // TODO: Avoid createChild if no region?
                if (sourceXSubsampling == 1) {
                    destination.setRect(0, dstY, sourceRow);
//                dataElements = raster.getDataElements(aoi.x, 0, aoi.width, 1, dataElements);
//                destination.setDataElements(offset.x, offset.y + (srcY - aoi.y) / sourceYSubsampling, aoi.width, 1, dataElements);
                }
                else {
                    for (int srcX = 0; srcX < sourceRow.getWidth(); srcX += sourceXSubsampling) {
                        dataElements = sourceRow.getDataElements(srcX, 0, dataElements);
                        int dstX = srcX / sourceXSubsampling;
                        destination.setDataElements(dstX, dstY, dataElements);
                    }
                }
            }

            processImageProgress(srcY * 100f / header.width);
            if (abortRequested()) {
                processReadAborted();
                break;
            }
        }
    }
62678
def rgb_to_sv(rgb):

    '''

    '''

    if not isinstance(rgb, np.ndarray):
        rgb = np.array(rgb)

    axis = len(rgb.shape)-1
    cmax = rgb.max(axis=axis).astype(np.float32)
    cmin = rgb.min(axis=axis).astype(np.float32)
    delta = cmax - cmin

    saturation = delta.astype(np.float32) / cmax.astype(np.float32)
    saturation = np.where(cmax == 0, 0, saturation)

    value = cmax/255.0

    return saturation, value
542884
function colorBlend(mode) {
    return function(first, second) {
        first = Color.color(first);
        second = Color.color(second);
        var ab = first.rgba[3];
        var as = second.rgba[3];
        var ar = as + ab * (1 - as);
        var rgba = [ 0, 0, 0, ar ]; // result

        var cb, cs, cr;
        for (var i = 0; i < 3; i++) {
            cb = first.rgba[i] / 255;
            cs = second.rgba[i] / 255;
            cr = mode(cb, cs);
            if (ar) {
                cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar;
            }
            rgba[i] = Math.round(cr * 255);
        }
        return Color.color(rgba);
    }
}
854566
def RGB(self, val):
        """"""
        # need to convert to normalized float
        val = np.atleast_1d(val).astype(np.float32) / 255.
        self.rgba = val
866919
def changecolourmode(self, newcolour):
        
        if type(newcolour) != type(0) and self.pilimage.mode != "RGB":
            if self.verbose :
                print "Switching to RGB !"
            self.pilimage = self.pilimage.convert("RGB")
            self.draw = None # important, we have to bebuild the draw object.
            self.makedraw()
756463
def scene_color(frames):
        """"""
        # "scene.color" <scene_id> <color>
        reader = MessageReader(frames)
        results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get()
        if results.command != "scene.color":
            raise MessageParserError("Command is not 'scene.color'")
        return (results.scene_id, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255]))
391705
def color_interp(data):
    """"""
    from rasterio.enums import ColorInterp as ci
    modes = {'L': [ci.gray],
             'LA': [ci.gray, ci.alpha],
             'YCbCr': [ci.Y, ci.Cb, ci.Cr],
             'YCbCrA': [ci.Y, ci.Cb, ci.Cr, ci.alpha]}

    try:
        mode = ''.join(data['bands'].values)
        return modes[mode]
    except KeyError:
        colors = {'R': ci.red,
                  'G': ci.green,
                  'B': ci.blue,
                  'A': ci.alpha,
                  'C': ci.cyan,
                  'M': ci.magenta,
                  'Y': ci.yellow,
                  'H': ci.hue,
                  'S': ci.saturation,
                  'L': ci.lightness,
                  'K': ci.black,
                  }
        return [colors[band] for band in data['bands'].values]
415656
def int_to_rgba(cls, rgba_int):
        """"""
        if rgba_int is None:
            return None, None, None, None
        alpha = rgba_int % 256
        blue = rgba_int / 256 % 256
        green = rgba_int / 256 / 256 % 256
        red = rgba_int / 256 / 256 / 256 % 256
        return (red, green, blue, alpha)
1341048
def to_color(self):
        
        color_data = np.repeat(self.data[:,:,np.newaxis], 3, axis=2)
        return ColorImage(color_data, self._frame)
605373
def guess_mode(self, data):
        
        # TODO: do we want to support dimensions being at the beginning of the array?
        if data.ndim == 2:
            return "L"
        elif data.shape[-1] == 3:
            return "RGB"
        elif data.shape[-1] == 4:
            return "RGBA"
        else:
            raise ValueError(
                "Un-supported shape for image conversion %s" % list(data.shape))
482363
function convertToFalseColorImage (element, colormap) {
  const enabledElement = getEnabledElement(element);


  return convertImageToFalseColorImage(enabledElement.image, colormap);
}
770840
def read_colormap(fh, byteorder, dtype, count, offsetsize):
    """"""
    cmap = fh.read_array(byteorder+dtype[-1], count)
    cmap.shape = (3, -1)
    return cmap
1042100
def palettize(self, colormap):
        

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

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

        def _palettize(data):
            # returns data and palette, only need data
            return colormap.palettize(data)[0]

        new_data = l_data.data.map_blocks(_palettize, dtype=l_data.dtype)
        self.palette = tuple(colormap.colors)

        if self.mode == "L":
            mode = "P"
        else:
            mode = "PA"
            new_data = da.concatenate([new_data, self.data.sel(bands=['A'])], axis=0)

        self.data.data = new_data
        self.data.coords['bands'] = list(mode)
658702
def imagemagick(color_count, img, magick_command):
    """"""
    flags = ["-resize", "25%", "-colors", str(color_count),
             "-unique-colors", "txt:-"]
    img += "[0]"

    return subprocess.check_output([*magick_command, img, *flags]).splitlines()
670562
def _value_to_color(value, cmap):
    """"""
    cm = plt.get_cmap(cmap)
    rgba = cm(value)
    return [int(round(255*v)) for v in rgba[0:3]]