Takes a 24-bit RGB :py:mod:`PIL.Image` and dumps it to the daisy-chained
        WS2812 neopixels.
331728
def display(self, image):
        
        assert(image.mode == self.mode)
        assert(image.size == self.size)

        ws = self._ws
        m = self._mapping
        for idx, (red, green, blue) in enumerate(image.getdata()):
            color = (red << 16) | (green << 8) | blue
            ws.ws2811_led_set(self._channel, m[idx], color)

        self._flush()
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
542014
def convert_images_to_pil(self, images, dither, nq=0, images_info=None):
        

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim == 3 and im.shape[2] == 3:
                    im = Image.fromarray(im, 'RGB')
                elif im.ndim == 3 and im.shape[2] == 4:
                    # im = Image.fromarray(im[:,:,:3],'RGB')
                    self.transparency = True
                    im = Image.fromarray(im[:, :, :4], 'RGBA')
                elif im.ndim == 2:
                    im = Image.fromarray(im, 'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA")  # NQ assumes RGBA
                nq_instance = NeuQuant(im, int(nq))  # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nq_instance.palette_image(), colors=255)
                else:
                    im = nq_instance.quantize(im, colors=255)  # Use to quantize the image itself

                self.transparency = True  # since NQ assumes transparency
                if self.transparency:
                    alpha = im.split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)
        else:
            # for index,im in enumerate(images):
            for i in range(len(images)):
                im = images[i].convert('RGB').convert('P', palette=Image.ADAPTIVE, dither=dither, colors=255)
                if self.transparency:
                    alpha = images[i].split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)

        # Done
        return images2
308534
def dump(self):
        """"""
        scan_lines = bytearray()
        for y in range(self.height):
            scan_lines.append(0)  # filter type 0 (None)
            scan_lines.extend(
                self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
            )
        # image represented as RGBA tuples, no interlacing
        return SIGNATURE + \
            self.pack_chunk(b'IHDR', struct.pack(b"!2I5B",
                                                 self.width, self.height,
                                                 8, 6, 0, 0, 0)) + \
            self.pack_chunk(b'IDAT', zlib.compress(bytes(scan_lines), 9)) + \
            self.pack_chunk(b'IEND', b'')
1171057
def to_uint8(self, data):
        
        np = util.get_module(
            "numpy", required="wandb.Image requires numpy if not supplying PIL Images: pip install numpy")

        # I think it's better to check the image range vs the data type, since many
        # image libraries will return floats between 0 and 255

        # some images have range -1...1 or 0-1
        dmin = np.min(data)
        if dmin < 0:
            data = (data - np.min(data)) / np.ptp(data)
        if np.max(data) <= 1.0:
            data = (data * 255).astype(np.int32)

        #assert issubclass(data.dtype.type, np.integer), 'Illegal image format.'
        return data.clip(0, 255).astype(np.uint8)
289599
def transform_pil_image(self, pil_image):
        '''
        
        '''
        max_width = min(self.dimensions[0] or float('inf'), pil_image.size[0])
        max_height = min(self.dimensions[1] or float('inf'), pil_image.size[1])
        max_dimensions = (max_width, max_height)

        pil_image.thumbnail(max_dimensions, Image.ANTIALIAS)
        return pil_image
703429
def render_image(self, rgbobj, dst_x, dst_y):
        
        self.logger.debug("redraw pixmap=%s" % (self.pixmap))
        if self.pixmap is None:
            return
        self.logger.debug("drawing to pixmap")

        # Prepare array for rendering
        arr = rgbobj.get_array(self.rgb_order, dtype=np.uint8)
        (height, width) = arr.shape[:2]

        return self._render_offscreen(self.pixmap, arr, dst_x, dst_y,
                                      width, height)
690971
def to_24bit_gray(mat: np.ndarray):
    """"""
    return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)
318811
def run(self):
        

        self.output('PanSharpened Image processing started for bands %s' % '-'.join(map(str, self.bands)),
                    normal=True, arrow=True)

        bands = self._read_bands()
        image_data = self._get_image_data()

        new_bands = self._generate_new_bands(image_data['shape'])

        bands[:3] = self._rescale(bands[:3])
        new_bands.append(numpy.empty(image_data['shape'], dtype=numpy.uint16))

        self._warp(image_data, bands, new_bands)

        # Bands are no longer needed
        del bands

        # Calculate pan band
        pan = self._pansize(new_bands)
        del self.bands[self.band8]
        del new_bands[self.band8]

        rasterio_options = {
            'driver': 'GTiff',
            'width': image_data['shape'][1],
            'height': image_data['shape'][0],
            'count': 3,
            'dtype': numpy.uint8,
            'nodata': 0,
            'transform': image_data['dst_transform'],
            'photometric': 'RGB',
            'crs': self.dst_crs
        }

        return self._write_to_file(new_bands, pan, **rasterio_options)
1310630
def _make_image(tensor):
    """"""
    assert isinstance(tensor, NDArray)
    if Image is None:
        raise ImportError('need to install PIL for visualizing images')
    height, width, channel = tensor.shape
    tensor = _make_numpy_array(tensor)
    image = Image.fromarray(tensor)
    output = io.BytesIO()
    image.save(output, format='PNG')
    image_string = output.getvalue()
    output.close()
    return Summary.Image(height=height, width=width, colorspace=channel,
                         encoded_image_string=image_string)
299624
def copy(self):
        ''' 

        '''
        return RGB(self.r, self.g, self.b, self.a)
727697
def rgb2hsv(arr):
    """"""
    arr = np.asanyarray(arr)
    if arr.ndim != 3 or arr.shape[2] != 3:
        raise ValueError("the input array must have a shape == (.,.,3)")
    arr = as_float_image(arr)

    out = np.empty_like(arr)

    # -- V channel
    out_v = arr.max(-1)

    # -- S channel
    delta = arr.ptp(-1)
    # Ignore warning for zero divided by zero
    old_settings = np.seterr(invalid='ignore')
    out_s = delta / out_v
    out_s[delta == 0.] = 0.

    # -- H channel
    # red is max
    idx = (arr[:, :, 0] == out_v)
    out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]

    # green is max
    idx = (arr[:, :, 1] == out_v)
    out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]

    # blue is max
    idx = (arr[:, :, 2] == out_v)
    out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
    out_h = (out[:, :, 0] / 6.) % 1.
    out_h[delta == 0.] = 0.

    np.seterr(**old_settings)

    # -- output
    out[:, :, 0] = out_h
    out[:, :, 1] = out_s
    out[:, :, 2] = out_v

    # remove NaN
    out[np.isnan(out)] = 0
    return out
131209
def castroData_from_pix_xy(self, xy, colwise=False):
        
        ipix = self._tsmap.xy_pix_to_ipix(xy, colwise)
        return self.castroData_from_ipix(ipix)
1131354
def rebin_image(bin_size, image, wht_map, sigma_bkg, ra_coords, dec_coords, idex_mask):
    
    numPix = int(len(image)/bin_size)
    numPix_precut = numPix * bin_size
    factor = int(len(image)/numPix)
    if not numPix * bin_size == len(image):
        image_precut = image[0:numPix_precut, 0:numPix_precut]
    else:
        image_precut = image
    image_resized = re_size(image_precut, factor)
    image_resized *= bin_size**2
    wht_map_resized = re_size(wht_map[0:numPix_precut, 0:numPix_precut], factor)
    sigma_bkg_resized = bin_size*sigma_bkg
    ra_coords_resized = re_size(ra_coords[0:numPix_precut, 0:numPix_precut], factor)
    dec_coords_resized = re_size(dec_coords[0:numPix_precut, 0:numPix_precut], factor)
    idex_mask_resized = re_size(idex_mask[0:numPix_precut, 0:numPix_precut], factor)
    idex_mask_resized[idex_mask_resized > 0] = 1
    return image_resized, wht_map_resized, sigma_bkg_resized, ra_coords_resized, dec_coords_resized, idex_mask_resized
943980
def getdarkimg(self,chip):
        
        sci_chip = self._image[self.scienceExt,chip]
        return np.ones(sci_chip.image_shape,dtype=sci_chip.image_dtype)*sci_chip.darkcurrent
1205760
def pix2ang(nside, ipix, nest=False, lonlat=False):
    """"""
    lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
    return _lonlat_to_healpy(lon, lat, lonlat=lonlat)
681338
def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4):
    '''
    
    '''
    ny,nx = u.shape
    sy, sx = np.mgrid[:float(ny):1,:float(nx):1]
    sx += u*t
    sy += v*t
    return cv2.remap(img.astype(np.float32), 
                    (sx).astype(np.float32),
                    (sy).astype(np.float32), interpolation)