Transfer the VOC color palette to an output mask for visualization.
336510
def palette(self, label_im):
        '''
        
        '''
        if label_im.ndim == 3:
            label_im = label_im[0]
        label = Image.fromarray(label_im, mode='P')
        label.palette = copy.copy(self.palette)
        return label
211643
def get_color_dist(c1, c2):
    
    return tuple(abs(v1 - v2) for v1, v2 in itertools.izip(c1, c2))
1080217
def get_fg_mask(bg_color, samples, options):

    ''''''

    s_bg, v_bg = rgb_to_sv(bg_color)
    s_samples, v_samples = rgb_to_sv(samples)

    s_diff = np.abs(s_bg - s_samples)
    v_diff = np.abs(v_bg - v_samples)

    return ((v_diff >= options.value_threshold) |
            (s_diff >= options.sat_threshold))
426153
public static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor)
    {
        return factoryGraphic.applyMask(imageBuffer, maskColor);
    }
861738
def _from_p(self, mode):
        

        self._check_modes(("P", "PA"))

        if self.mode.endswith("A"):
            alpha = self.channels[-1]
        else:
            alpha = None

        chans = []
        cdfs = []

        color_chan = self.channels[0]

        for i in range(len(self.palette[0])):
            cdfs.append(np.zeros(len(self.palette)))
            for j in range(len(self.palette)):
                cdfs[i][j] = self.palette[j][i]
            new_chn = np.ma.array(np.interp(color_chan,
                                            np.arange(len(self.palette)),
                                            cdfs[i]),
                                  mask=color_chan.mask)
            chans.append(new_chn)

        if self.fill_value is not None:
            if alpha is not None:
                fill_alpha = self.fill_value[-1]
                self.fill_value = list(self.palette[int(self.fill_value[0])])
                self.fill_value += [fill_alpha]
            else:
                self.fill_value = list(self.palette[int(self.fill_value[0])])

        self.mode = self._secondary_mode
        self.channels = chans
        if alpha is not None:
            self.channels.append(alpha)
            self.mode = self.mode + "A"

        self.convert(mode)
1054827
def draw_dithered_color(cb, x, y, palette, dither, n, n_max, crosshairs_coord=None):
    
    i = n * (len(palette) - 1) / n_max
    c1 = palette[int(math.floor(i))]
    c2 = palette[int(math.ceil(i))]
    value = i - int(math.floor(i))

    symbol = dither_symbol(value, dither)

    if crosshairs_coord is not None:
        old_symbol = symbol
        symbol, crosshairs = get_crosshairs_symbol(x, y, old_symbol, crosshairs_coord)
        if crosshairs:
            sorted_palette = sort_palette(palette)
            if old_symbol == DITHER_TYPES[dither][1][0]:
                c2 = c1
            sorted_index = sorted_palette.index(c2)
            if sorted_index > len(sorted_palette) // 2:
                c1 = sorted_palette[0]
            else:
                c1 = sorted_palette[-1]

    cb.put(x, y, symbol, c1(), c2())
1290118
def cutout(vol, requested_bbox, steps, channel_slice=slice(None), parallel=1, 
  shared_memory_location=None, output_to_shared_memory=False):
  """"""
  global fs_lock

  cloudpath_bbox = requested_bbox.expand_to_chunk_size(vol.underlying, offset=vol.voxel_offset)
  cloudpath_bbox = Bbox.clamp(cloudpath_bbox, vol.bounds)
  cloudpaths = list(chunknames(cloudpath_bbox, vol.bounds, vol.key, vol.underlying))
  shape = list(requested_bbox.size3()) + [ vol.num_channels ]

  handle = None

  if parallel == 1:
    if output_to_shared_memory:
      array_like, renderbuffer = shm.bbox2array(vol, requested_bbox, 
        location=shared_memory_location, lock=fs_lock)
      shm.track_mmap(array_like)
    else:
      renderbuffer = np.zeros(shape=shape, dtype=vol.dtype, order='F')

    def process(img3d, bbox):
      shade(renderbuffer, requested_bbox, img3d, bbox)
    download_multiple(vol, cloudpaths, fn=process)
  else:
    handle, renderbuffer = multi_process_cutout(vol, requested_bbox, cloudpaths, parallel, 
      shared_memory_location, output_to_shared_memory)
  
  renderbuffer = renderbuffer[ ::steps.x, ::steps.y, ::steps.z, channel_slice ]
  return VolumeCutout.from_volume(vol, renderbuffer, requested_bbox, handle=handle)
943799
def color_worker(srcs, window, ij, args):
    """"""
    src = srcs[0]
    arr = src.read(window=window)
    arr = to_math_type(arr)

    for func in parse_operations(args["ops_string"]):
        arr = func(arr)

    # scaled 0 to 1, now scale to outtype
    return scale_dtype(arr, args["out_dtype"])
932800
public static void drawMasked(Bitmap src, Drawable mask, Bitmap dest) {
        drawMasked(src, mask, dest, CLEAR_COLOR);
    }
12130
def plot_masks(mask_1, mask_2, mask_3):
    """"""
    fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5))
    for ax in [ax1, ax2, ax3]:
        ax.grid(False)
        ax.set_xticks([])
        ax.set_yticks([])
    ax1.set_title("Type 1")
    ax1.imshow(mask_1, cmap='viridis')
    ax2.set_title("Type 2")
    ax2.imshow(mask_2, cmap='viridis')
    ax3.set_title("Type 3")
    ax3.imshow(mask_3, cmap='viridis')
    return ax1, ax2, ax3
15631
def applyColorMap(gray, cmap='flame'):
    '''
    
    '''
    # TODO:implement more cmaps
    if cmap != 'flame':
        raise NotImplemented
    # TODO: make better
    mx = 256  # if gray.dtype==np.uint8 else 65535
    lut = np.empty(shape=(256, 3))
    cmap = (
        # taken from pyqtgraph GradientEditorItem
        (0, (0, 0, 0)),
        (0.2, (7, 0, 220)),
        (0.5, (236, 0, 134)),
        (0.8, (246, 246, 0)),
        (1.0, (255, 255, 255))
    )
    # build lookup table:
    lastval, lastcol = cmap[0]
    for step, col in cmap[1:]:
        val = int(step * mx)
        for i in range(3):
            lut[lastval:val, i] = np.linspace(
                lastcol[i], col[i], val - lastval)

        lastcol = col
        lastval = val

    s0, s1 = gray.shape
    out = np.empty(shape=(s0, s1, 3), dtype=np.uint8)

    for i in range(3):
        out[..., i] = cv2.LUT(gray, lut[:, i])
    return out
338574
def boolMasksToImage(masks):
    '''
    
    '''
    assert len(masks) <= 8, 'can only transform up to 8 masks into image'
    masks = np.asarray(masks, dtype=np.uint8)
    assert masks.ndim == 3, 'layers need to be stack of 2d arrays'
    return np.packbits(masks, axis=0)[0].T
807325
function translateColor(colorArr, variationName, execMode) {
  const [colorVar, alpha] = colorArr;

  // returns the real color representation
  if (!options.palette) {
    options.palette = getColorPalette();
  }

  const underlineColor = options.palette[variationName][colorVar];

  if (!underlineColor) {
    // variable is not mandatory in non-default variations
    if (variationName !== defaultVariation) {
      return null;
    }
    throw new Error(
      `The variable name '${colorVar}' doesn't exists in your palette.`,
    );
  }

  switch (execMode) {
    case ExecutionMode.CSS_COLOR:
      // with default alpha - just returns the color
      if (alpha === '1') {
        return rgb2hex(underlineColor).hex;
      }
      // with custom alpha, convert it to rgba
      const rgbaColor = hexToRgba(rgb2hex(underlineColor).hex, alpha);
      return rgbaColor;
    default:
      if (alpha === 1) {
        return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
        //return `var(--bolt-theme-${colorVar})`; // @todo: re-evaluate if hex values should ever get outputted here
      } else {
        return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
      }
  }
}
950389
public static void drawMasked(Bitmap src, Drawable mask, Bitmap dest, int clearColor) {
        clearBitmap(dest, clearColor);
        Canvas canvas = new Canvas(dest);

        canvas.drawBitmap(src,
                new Rect(0, 0, src.getWidth(), src.getHeight()),
                new Rect(0, 0, dest.getWidth(), dest.getHeight()),
                new Paint(Paint.FILTER_BITMAP_FLAG));

        if (mask instanceof BitmapDrawable) {
            ((BitmapDrawable) mask).getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        } else if (mask instanceof NinePatchDrawable) {
            ((NinePatchDrawable) mask).getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        } else {
            throw new RuntimeException("Supported only BitmapDrawable or NinePatchDrawable");
        }
        mask.setBounds(0, 0, mask.getIntrinsicWidth(), mask.getIntrinsicHeight());
        mask.draw(canvas);
        canvas.setBitmap(null);
    }
43951
def drawMask(self,ax=None, mask=None, mtype='maglim'):
        
        if not ax: ax = plt.gca()
        if mask is None:
            mask = ugali.analysis.loglike.createMask(self.config,roi=self.roi)

        mask_map = hp.UNSEEN*np.ones(hp.nside2npix(self.nside))
        if mtype.lower() == 'maglim':
            mask_map[mask.roi.pixels] = mask.mask_1.mask_roi_sparse
        elif mtype.lower() == 'fracdet':
            mask_map[mask.roi.pixels] = mask.mask_1.frac_roi_sparse
        else:
            raise Exception("Unrecognized type: %s"%mtype)
        masked = (mask_map==hp.UNSEEN) | (mask_map==0)
        mask_map = np.ma.array(mask_map,mask=masked,fill_value=np.nan)

        im = drawHealpixMap(mask_map,self.lon,self.lat,self.radius,coord=self.coord)

        try: cbar = ax.cax.colorbar(im)
        except: cbar = plt.colorbar(im)
        cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(),rotation=90)
        ax.annotate(mtype,**self.label_kwargs)
        return im
23420
public static void RGB_to_PLU8(Picture input, Planar<GrayU8> output) {
		if( input.getColor() != ColorSpace.RGB )
			throw new RuntimeException("Unexpected input color space!");
		if( output.getNumBands() != 3 )
			throw new RuntimeException("Unexpected number of bands in output image!");

		output.reshape(input.getWidth(),input.getHeight());

		int dataIn[] = input.getData()[0];

		GrayU8 out0 = output.getBand(0);
		GrayU8 out1 = output.getBand(1);
		GrayU8 out2 = output.getBand(2);

		int indexIn = 0;
		int indexOut = 0;
		for (int i = 0; i < output.height; i++) {
			for (int j = 0; j < output.width; j++, indexOut++ ) {
				int r = dataIn[indexIn++];
				int g = dataIn[indexIn++];
				int b = dataIn[indexIn++];

				out2.data[indexOut] = (byte)r;
				out1.data[indexOut] = (byte)g;
				out0.data[indexOut] = (byte)b;
			}
		}
	}
775753
def print_colors(palette, outfile="Palette.png"):
    
    fig = plt.figure()
    ax = fig.add_subplot(111)

    xmax = 20 * (len(palette) + 1)
    x1s = np.arange(0, xmax, 20)
    xintervals = [10] * len(palette)
    xx = zip(x1s, xintervals)
    ax.broken_barh(xx, (5, 10), facecolors=palette)

    ax.set_ylim(0, 20)
    ax.set_xlim(0, xmax)
    ax.set_axis_off()

    savefig(outfile)