Get PIL mode from ColorMode.
429989
def get_pil_mode(value, alpha=False):
    """"""
    name = {
        'GRAYSCALE': 'L',
        'BITMAP': '1',
        'DUOTONE': 'L',
        'INDEXED': 'P',
    }.get(value, value)
    if alpha and name in ('L', 'RGB'):
        name += 'A'
    return name
621589
def _rgb2ycbcr(self, mode):
        """"""

        self._check_modes(("RGB", "RGBA"))

        (self.channels[0], self.channels[1], self.channels[2]) = \
            rgb2ycbcr(self.channels[0],
                      self.channels[1],
                      self.channels[2])

        if self.fill_value is not None:
            self.fill_value[0:3] = rgb2ycbcr(self.fill_value[0],
                                             self.fill_value[1],
                                             self.fill_value[2])

        self.mode = mode
1015110
def rgChromaticity(img):
    '''
    
    '''
    out = _calc(img)
    if img.dtype == np.uint8:
        out = (255 * out).astype(np.uint8)
    return out
721007
def extract_colors(
        filename_or_img, min_saturation=config.MIN_SATURATION,
        min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS,
        min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED):
    
    if Image.isImageType(filename_or_img):
        im = filename_or_img
    else:
        im = Image.open(filename_or_img)

    # get point color count
    if im.mode != 'RGB':
        im = im.convert('RGB')
    im = autocrop(im, config.WHITE)  # assume white box
    im = im.convert(
        'P', palette=Image.ADAPTIVE, colors=n_quantized).convert('RGB')
    dist = Counter({color: count for count, color
                    in im.getcolors(n_quantized)})
    n_pixels = mul(*im.size)

    # aggregate colors
    to_canonical = {config.WHITE: config.WHITE, config.BLACK: config.BLACK}
    aggregated = Counter({config.WHITE: 0, config.BLACK: 0})
    sorted_cols = sorted(dist.items(), key=itemgetter(1), reverse=True)
    for c, n in sorted_cols:
        if c in aggregated:
            # exact match!
            aggregated[c] += n
        else:
            d, nearest = min((distance(c, alt), alt) for alt in aggregated)
            if d < min_distance:
                # nearby match
                aggregated[nearest] += n
                to_canonical[c] = nearest
            else:
                # no nearby match
                aggregated[c] = n
                to_canonical[c] = c

    # order by prominence
    colors = sorted(
        [Color(c, n / float(n_pixels)) for c, n in aggregated.items()],
        key=attrgetter('prominence'), reverse=True)

    colors, bg_color = detect_background(im, colors, to_canonical)

    # keep any color which meets the minimum saturation
    sat_colors = [c for c in colors if meets_min_saturation(c, min_saturation)]
    if bg_color and not meets_min_saturation(bg_color, min_saturation):
        bg_color = None
    if sat_colors:
        colors = sat_colors
    else:
        # keep at least one color
        colors = colors[:1]

    # keep any color within 10% of the majority color
    color_list = []
    color_count = 0

    for color in colors:
        if color.prominence >= colors[0].prominence * min_prominence:
            color_list.append(color)
            color_count += 1

        if color_count >= max_colors:
            break

    return Palette(color_list, bg_color)
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))
366246
def parse_mode(mode, default_bitdepth=None):
    """"""
    # few special cases
    if mode == 'P':
        # Don't know what is pallette
        raise Error('Unknown colour mode:' + mode)
    elif mode == '1':
        # Logical
        return (True, False, 1)
    elif mode == 'I':
        # Integer
        return (True, False, 16)
    # here we go
    if mode.startswith('L'):
        grayscale = True
        mode = mode[1:]
    elif mode.startswith('RGB'):
        grayscale = False
        mode = mode[3:]
    else:
        raise Error('Unknown colour mode:' + mode)

    if mode.startswith('A'):
        alpha = True
        mode = mode[1:]
    else:
        alpha = False

    bitdepth = default_bitdepth
    if mode.startswith(';'):
        mode = mode[1:]
    if mode:
        try:
            bitdepth = int(mode)
        except (TypeError, ValueError):
            raise Error('Unsupported bitdepth mode:' + mode)
    return (grayscale, alpha, bitdepth)
1077759
def getOverlayTextureColorSpace(self, ulOverlayHandle):
        """"""

        fn = self.function_table.getOverlayTextureColorSpace
        peTextureColorSpace = EColorSpace()
        result = fn(ulOverlayHandle, byref(peTextureColorSpace))
        return result, peTextureColorSpace
717074
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
    """"""

    img = load_image_from_disk(img_spec)

    if not np.issubdtype(img.dtype, np.floating):
        img = img.astype('float32')

    if ensure_num_dim == 3:
        img = check_image_is_3d(img)
    elif ensure_num_dim == 4:
        img = check_image_is_4d(img)

    return threshold_image(img, bkground_thresh)
667336
def _rgbtomask(self, obj):
        """"""
        dat = obj.get_image().get_data()  # RGB arrays
        return dat.sum(axis=2).astype(np.bool)
1265497
def getDimensionForImage(filename, maxsize):
    """"""
    try:
        from PIL import Image
    except ImportError:
        return None
    img = Image.open(filename)
    width, height = img.size
    if width > maxsize[0] or height > maxsize[1]:
        img.thumbnail(maxsize)
        out.info("Downscaled display size from %s to %s" % ((width, height), img.size))
    return img.size
1253456
def check_color(cls, raw_image):
        
        # sum(img.convert("L").getextrema()) in (0, 2)
        extrema = raw_image.convert("L").getextrema()
        if extrema == (255, 255): # all white
            raise cls.MonoImageException
683768
def colour_rgb(self):
        """"""
        hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
        return BulbDevice._hexvalue_to_rgb(hexvalue)
319707
def convert(self, mode):
        
        if mode == self.mode:
            return

        if mode not in ["L", "LA", "RGB", "RGBA",
                        "YCbCr", "YCbCrA", "P", "PA"]:
            raise ValueError("Mode %s not recognized." % (mode))

        if self.is_empty():
            self.mode = mode
            return

        if mode == self.mode + "A":
            self.channels.append(np.ma.ones(self.channels[0].shape))
            if self.fill_value is not None:
                self.fill_value += [1]
            self.mode = mode

        elif mode + "A" == self.mode:
            self.channels = self.channels[:-1]
            if self.fill_value is not None:
                self.fill_value = self.fill_value[:-1]
            self.mode = mode

        elif mode.endswith("A") and not self.mode.endswith("A"):
            self.convert(self.mode + "A")
            self.convert(mode)

        elif self.mode.endswith("A") and not mode.endswith("A"):
            self.convert(self.mode[:-1])
            self.convert(mode)

        else:
            cases = {
                "RGB": {"YCbCr": self._rgb2ycbcr,
                        "L": self._rgb2l,
                        "P": self._to_p},
                "RGBA": {"YCbCrA": self._rgb2ycbcr,
                         "LA": self._rgb2l,
                         "PA": self._to_p},
                "YCbCr": {"RGB": self._ycbcr2rgb,
                          "L": self._ycbcr2l,
                          "P": self._to_p},
                "YCbCrA": {"RGBA": self._ycbcr2rgb,
                           "LA": self._ycbcr2l,
                           "PA": self._to_p},
                "L": {"RGB": self._l2rgb,
                      "YCbCr": self._l2ycbcr,
                      "P": self._to_p},
                "LA": {"RGBA": self._l2rgb,
                       "YCbCrA": self._l2ycbcr,
                       "PA": self._to_p},
                "P": {"RGB": self._from_p,
                      "YCbCr": self._from_p,
                      "L": self._from_p},
                "PA": {"RGBA": self._from_p,
                       "YCbCrA": self._from_p,
                       "LA": self._from_p}}
            try:
                cases[self.mode][mode](mode)
            except KeyError:
                raise ValueError("Conversion from %s to %s not implemented !"
                                 % (self.mode, mode))
90095
def color_mod(self):
        
        rgb = ffi.new('Uint8[]', 3)
        check_int_err(lib.SDL_GetTextureColorMod(self._ptr, rgb + 0, rgb + 1, rgb + 2))
        return (rgb[0], rgb[1], rgb[2])
386187
function getNativeModes() {
    if (typeof document === 'undefined') {
        return {};
    }
    var i, mode, darken, ok;
    var nativeModes = {};
    var dCanvas = document.createElement('canvas');
    var ctx = dCanvas.getContext('2d');

    if (!ctx) { return {}; }

    var native = ['source-over', 'source-in', 'source-out', 'source-atop',
            'destination-over', 'destination-in', 'destination-out',
            'destination-atop', 'lighter', 'darker', 'copy', 'xor'];

    var maybeNative = ['multiply', 'screen', 'overlay', 'soft-light', 'hard-light',
            'color-dodge', 'color-burn', 'darken', 'lighten', 'difference',
            'exclusion', 'hue', 'saturation', 'luminosity', 'color',
            'add', 'subtract', 'average', 'negation'];

    var nonNative = ['divide', 'darker-color', 'lighter-color', 'linear-burn', 'linear-light',
            'vivid-light', 'pin-light', 'hard-mix'];

    for (i = 0; i < native.length; i += 1) {
        nativeModes[native[i]] = true;
    }
    for (i = 0; i < nonNative.length; i += 1) {
        nativeModes[nonNative[i]] = false;
    }
    dCanvas.width = 1;
    dCanvas.height = 1;
    for (i = 0; i < maybeNative.length; i += 1) {
        mode = maybeNative[i];
        darken = mode === 'darken';
        ok = false;
        ctx.save();
        try {
            ctx.fillStyle = darken ? '#300' : '#a00';
            ctx.fillRect(0, 0, 1, 1);
            ctx.globalCompositeOperation = mode;
            if (ctx.globalCompositeOperation === mode) {
                ctx.fillStyle = darken ? '#a00' : '#300';
                ctx.fillRect(0, 0, 1, 1);
                ok = ctx.getImageData(0, 0, 1, 1).data[0] !== (darken ? 170 : 51);
            }
        } catch (e) {
        }
        ctx.restore();
        nativeModes[mode] = ok;
    }

    addAliases(nativeModes);

    return nativeModes;
}
101537
def _get_text_color(self):
        """"""

        color = self.code_array.cell_attributes[self.key]["textcolor"]
        return tuple(c / 255.0 for c in color_pack2rgb(color))
1326524
def get_color(self):
        """"""
        self.get_status()
        try:
            self.color = self.data['color']
            self.mode = self.data['mode']
        except TypeError:
            self.color = 0
            self.mode = ''

        return {'color': self.color, 'mode': self.mode}