Returns the *closest* depth file from an RGB filename
323315
def depth_file_for_rgb_file(rgb_filename, rgb_file_list, depth_file_list):
        """"""
        (root, filename) = os.path.split(rgb_filename)
        rgb_timestamps = np.array(Kinect.timestamps_from_file_list(rgb_file_list))
        depth_timestamps = np.array(Kinect.timestamps_from_file_list(depth_file_list))
        needle_ts = rgb_timestamps[rgb_file_list.index(rgb_filename)]
        haystack_idx = np.argmin(np.abs(depth_timestamps - needle_ts))
        depth_filename = depth_file_list[haystack_idx]
        return depth_filename
303272
def _get_extended_palette_entry(self, name, index, is_hex=False):
        '''  '''
        values = None
        is_fbterm = (env.TERM == 'fbterm')  # sigh

        if 'extended' in self._palette_support:  # build entry
            if is_hex:
                index = str(find_nearest_color_hexstr(index,
                                                      method=self._dg_method))
            start_codes = self._start_codes_extended
            if is_fbterm:
                start_codes = self._start_codes_extended_fbterm

            values = [start_codes, index]

        # downgrade section
        elif 'basic' in self._palette_support:
            if is_hex:
                nearest_idx = find_nearest_color_hexstr(index, color_table4,
                                                        method=self._dg_method)
            else:
                from .color_tables import index_to_rgb8  # find rgb for idx
                nearest_idx = find_nearest_color_index(*index_to_rgb8[index],
                                                       color_table=color_table4,
                                                       method=self._dg_method)
            values = self._index_to_ansi_values(nearest_idx)

        return (self._create_entry(name, values, fbterm=is_fbterm)
                if values else empty)
362283
def Images2Rgbd(rgb, d):
    '''
    

    '''
    data = Rgbd()
    data.color=imageMsg2Image(rgb)
    data.depth=imageMsg2Image(d)
    data.timeStamp = rgb.header.stamp.secs + (rgb.header.stamp.nsecs *1e-9)
    return data
689829
def getPixels(self):
        
        array = self.toArray()
        (width, height, depth) = array.size
        for x in range(width):
            for y in range(height):
                yield Pixel(array, x, y)
1134081
def convert_to_rgb(img):
    
    if img.mode == 'CMYK' and HAS_PROFILE_TO_PROFILE:
        profile_dir = os.path.join(os.path.dirname(__file__), 'profiles')
        input_profile = os.path.join(profile_dir, "USWebUncoated.icc")
        output_profile = os.path.join(profile_dir, "sRGB_v4_ICC_preference.icc")
        return profileToProfile(img, input_profile, output_profile, outputMode='RGB')
    return img
1257748
def _image2array(filepath):
    '''
    
    '''
    im = Pimage.open(filepath).convert('RGB')
    (width, height) = im.size
    _r = np.array(list(im.getdata(0)))/255.0
    _g = np.array(list(im.getdata(1)))/255.0
    _b = np.array(list(im.getdata(2)))/255.0
    _r = _r.reshape((height, width))
    _g = _g.reshape((height, width))
    _b = _b.reshape((height, width))
    return _r, _g, _b
667610
def rgb2short(r, g, b):
    
    # Using list of snap points, convert RGB value to cube indexes
    r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)]

    # Simple colorcube transform
    return (r * 36) + (g * 6) + b + 16
344572
function parse_PtgRef3d(blob, length, opts) {
	var type = (blob[blob.l] & 0x60)>>5;
	blob.l += 1;
	var ixti = blob.read_shift(2); // XtiIndex
	if(opts && opts.biff == 5) blob.l += 12;
	var loc = parse_RgceLoc(blob, 0, opts); // TODO: or RgceLocRel
	return [type, ixti, loc];
}
810777
def background_color(self, node, depth):
        """"""
        if self.color_mapping is None:
            self.color_mapping = {}
        color = self.color_mapping.get(node.key)
        if color is None:
            depth = len(self.color_mapping)
            red = (depth * 10) % 255
            green = 200 - ((depth * 5) % 200)
            blue = (depth * 25) % 200
            self.color_mapping[node.key] = color = wx.Colour(red, green, blue)
        return color
554948
private void RGBtoHSV(float red, float green, float blue) {

        float min = 0;
        float max = 0;
        float delta = 0;

        min = MIN(red, green, blue);
        max = MAX(red, green, blue);

        m_bri = max; // v

        delta = max - min;

        if (max != 0) {
            m_sat = delta / max; // s
        } else {
            m_sat = 0;
            m_hue = 0;
            return;
        }

        if (delta == 0) {
            m_hue = 0;
            return;
        }

        if (red == max) {
            m_hue = (green - blue) / delta;
        } else if (green == max) {
            m_hue = 2 + ((blue - red) / delta);
        } else {
            m_hue = 4 + ((red - green) / delta);
        }

        m_hue *= 60;

        if (m_hue < 0) {
            m_hue += 360;
        }
    }
619126
def from_color_and_depth(color_im, depth_im):
        
        # check shape
        if color_im.height != depth_im.height or color_im.width != depth_im.width:
            raise ValueError('Color and depth images must have the same shape')

        # check frame
        if color_im.frame != depth_im.frame:
            raise ValueError('Color and depth images must have the same frame')

        # form composite data
        rgbd_data = np.zeros([color_im.height, color_im.width, 4])
        rgbd_data[:, :, :3] = color_im.data.astype(np.float64)
        rgbd_data[:, :, 3] = depth_im.data
        return RgbdImage(rgbd_data, frame=color_im.frame)
79711
def getBoundsColor(self, nNumOutputColors, flCollisionBoundsFadeDistance):
        """"""

        fn = self.function_table.getBoundsColor
        pOutputColorArray = HmdColor_t()
        pOutputCameraColor = HmdColor_t()
        fn(byref(pOutputColorArray), nNumOutputColors, flCollisionBoundsFadeDistance, byref(pOutputCameraColor))
        return pOutputColorArray, pOutputCameraColor
827583
def rgb_to_short(rgb, mapping):
    """"""
    # Thanks to Micah Elliott (http://MicahElliott.com) for colortrans.py
    rgb = rgb.lstrip('#') if rgb.startswith('#') else rgb
    incs = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
    # Break 6-char RGB code into 3 integer vals.
    parts = [int(h, 16) for h in re.split(r'(..)(..)(..)', rgb)[1:4]]
    res = []
    for part in parts:
        i = 0
        while i < len(incs)-1:
            s, b = incs[i], incs[i+1]  # smaller, bigger
            if s <= part <= b:
                s1 = abs(s - part)
                b1 = abs(b - part)
                if s1 < b1: closest = s
                else: closest = b
                res.append(closest)
                break
            i += 1
    res = ''.join([ ('%02.x' % i) for i in res ])
    equiv = mapping[res]
    return equiv, res
1173597
def from_grayscale_and_depth(gray_im, depth_im):
        
        # check shape
        if gray_im.height != depth_im.height or gray_im.width != depth_im.width:
            raise ValueError(
                'Grayscale and depth images must have the same shape')

        # check frame
        if gray_im.frame != depth_im.frame:
            raise ValueError(
                'Grayscale and depth images must have the same frame')

        # form composite data
        gd_data = np.zeros([gray_im.height, gray_im.width, 2])
        gd_data[:, :, 0] = gray_im.data.astype(np.float64)
        gd_data[:, :, 1] = depth_im.data
        return GdImage(gd_data, frame=gray_im.frame)
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)
1179174
def get_depth_pmf(self, depth_bins, default_depth=5.0, bootstrap=None):
        
        if len(self.data['depth']) == 0:
            # If depth information is missing
            return PMF([(1.0, default_depth)])
        # Get the depth distribution
        depth_hist = self.get_depth_distribution(depth_bins,
                                                 normalisation=True,
                                                 bootstrap=bootstrap)
        # If the histogram does not sum to 1.0 then remove the difference
        # from the lowest bin
        depth_hist = np.around(depth_hist, 3)
        while depth_hist.sum() - 1.0:
            depth_hist[-1] -= depth_hist.sum() - 1.0
            depth_hist = np.around(depth_hist, 3)

        pmf_list = []
        for iloc, prob in enumerate(depth_hist):
            pmf_list.append((prob,
                             (depth_bins[iloc] + depth_bins[iloc + 1]) / 2.0))
        return PMF(pmf_list)
177232
def gdk(self, color):
        """"""
        c = self.parse(color)
        return gdk.Color.from_floats(c)