Adjust image balance and contrast
559797
def lighting(im, b, c):
    
    if b==0 and c==1: return im
    mu = np.average(im)
    return np.clip((im-mu)*c+mu+b,0.,1.).astype(np.float32)
630882
def contrast(self, value):
        
        assert(0x00 <= value <= 0xFF)
        self._contrast = value
        self._ws.ws2811_channel_t_brightness_set(self._channel, value)
        self._flush()
1357249
def get(img, light=False):
    """"""
    colors = gen_colors(img)
    return adjust(colors, light)
533005
def composite(
    background_image,
    foreground_image,
    foreground_width_ratio=0.25,
    foreground_position=(0.0, 0.0),
):
    """"""

    if foreground_width_ratio <= 0:
        return background_image

    composite = background_image.copy()
    width = int(foreground_width_ratio * background_image.shape[1])
    foreground_resized = resize(foreground_image, width)
    size = foreground_resized.shape

    x = int(foreground_position[1] * (background_image.shape[1] - size[1]))
    y = int(foreground_position[0] * (background_image.shape[0] - size[0]))

    # TODO: warn if resulting coordinates are out of bounds?
    composite[y : y + size[0], x : x + size[1]] = foreground_resized

    return composite
362556
def correct(self, img):
        '''
         
        '''
        print("CORRECT PERSPECTIVE ...")
        self.img = imread(img)

        if not self._homography_is_fixed:
            self._homography = None
        h = self.homography

        if self.opts['do_correctIntensity']:
            tf = self.tiltFactor()
            self.img = np.asfarray(self.img)
            if self.img.ndim == 3:
                for col in range(self.img.shape[2]):
                    self.img[..., col] /= tf
            else:
                self.img = self.img / tf
        warped = cv2.warpPerspective(self.img,
                                     h,
                                     self._newBorders[::-1],
                                     flags=cv2.INTER_LANCZOS4,
                                     **self.opts['cv2_opts'])
        return warped
480973
def _setup_images(directory, brightness, saturation, hue, preserve_transparency):
        
        for file_name in os.listdir(directory):
            with open(os.path.join(directory, file_name), "rb") as fi:
                image = Image.open(fi).convert("RGBA")
            # Only perform required operations
            if brightness != 1.0:
                enhancer = ImageEnhance.Brightness(image)
                image = enhancer.enhance(brightness)
            if saturation != 1.0:
                enhancer = ImageEnhance.Color(image)
                image = enhancer.enhance(saturation)
            if hue != 1.0:
                image = imgops.shift_hue(image, hue)
            if preserve_transparency is True:
                image = imgops.make_transparent(image)
            # Save the new image
            image.save(os.path.join(directory, file_name.replace("gif", "png")))
            image.close()
        for file_name in (item for item in os.listdir(directory) if item.endswith(".gif")):
            os.remove(os.path.join(directory, file_name))
145800
def ms_contrast(self, viewer, event, data_x, data_y, msg=True):
        
        if not self.cancmap:
            return True
        msg = self.settings.get('msg_contrast', msg)

        x, y = self.get_win_xy(viewer)

        if event.state == 'move':
            self._tweak_colormap(viewer, x, y, 'preview')

        elif event.state == 'down':
            self._start_x, self._start_y = x, y
            if msg:
                viewer.onscreen_message(
                    "Shift and stretch colormap (drag mouse)", delay=1.0)
        else:
            viewer.onscreen_message(None)
        return True
391052
def transpose_image(self, image):
        
        EXIF_ORIENTATION_STEPS = {
            1: [],
            2: ['FLIP_LEFT_RIGHT'],
            3: ['ROTATE_180'],
            4: ['FLIP_TOP_BOTTOM'],
            5: ['ROTATE_270', 'FLIP_LEFT_RIGHT'],
            6: ['ROTATE_270'],
            7: ['ROTATE_90', 'FLIP_LEFT_RIGHT'],
            8: ['ROTATE_90'],
        }
        try:
            orientation = image._getexif()[0x0112]
            ops = EXIF_ORIENTATION_STEPS[orientation]
        except:
            ops = []
        for method in ops:
            image = image.transpose(getattr(Image, method))
        return image
1222242
def blit(self, image, x, y):
        """"""
        # adjust the position with the local bbox
        x += self.font_bbox[2] - self.bbox[2]
        y += self.font_bbox[3] - self.bbox[3]
        x += self.font_bbox[0] - self.bbox[0]
        y += self.font_bbox[1] - self.bbox[1]
        image[y:y+self.height, x:x+self.width] = self.bitmap * 255
1020877
private void scaleToOutputResolution(Image image) {

        float factor = m_sharedContext.getDotsPerPixel();
        if (factor != 1.0f) {
            image.scaleAbsolute(image.getPlainWidth() * factor, image.getPlainHeight() * factor);
        }
    }
726229
def overlay(image, color):
    
    width, height = image.size
    im = Image.new("RGBA", (width, height), color)
    preview = Image.alpha_composite(image, im)
    return preview
440195
def rgb2gray(img):
    """"""
    T = np.linalg.inv(np.array([
        [1.0,  0.956,  0.621],
        [1.0, -0.272, -0.647],
        [1.0, -1.106,  1.703],
    ]))
    r_c, g_c, b_c = T[0]
    r, g, b = np.rollaxis(as_float_image(img), axis=-1)
    return r_c * r + g_c * g + b_c * b
1291900
def preprocess(self, image):
        
        image = super(max7219, self).preprocess(image)

        if self._correction_angle != 0:
            image = image.copy()
            for y in range(0, self._h, 8):
                for x in range(0, self._w, 8):
                    box = (x, y, x + 8, y + 8)
                    rotated_block = image.crop(box).rotate(self._correction_angle)
                    image.paste(rotated_block, box)
        if self.blocks_arranged_in_reverse_order:
            old_image = image.copy()
            for y in range(8):
                for x in range(8):
                    for i in range(self.cascaded):
                        image.putpixel((8 * (self.cascaded - 1) - i * 8 + x, y), old_image.getpixel((i * 8 + x, y)))

        return image
720290
def enforce_vertical_symmetry(pixmap):
    ''''''
    mirror = []
    for item in pixmap:
        y = item[0]
        x = item[1]

        if x <= IMAGE_APEX:
            diff_x = diff(x, IMAGE_APEX)
            mirror.append((y, x + (2 * diff_x) - 1))

        if x > IMAGE_APEX:
            diff_x = diff(x, IMAGE_APEX)
            mirror.append((y, x - (2 * diff_x) - 1))

    return mirror + pixmap
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)
776551
def imscatter(images, positions):
    '''
        
    '''
    positions = np.array(positions)

    bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images])
    tops = bottoms + np.array([im.shape[1] for im in images])

    lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images])
    rigths = lefts + np.array([im.shape[0] for im in images])

    most_bottom = int(np.floor(bottoms.min()))
    most_top = int(np.ceil(tops.max()))

    most_left = int(np.floor(lefts.min()))
    most_right = int(np.ceil(rigths.max()))

    scatter_image = np.zeros(
        [most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype)

    # shift, now all from zero
    positions -= [most_left, most_bottom]

    for im, pos in zip(images, positions):

        xl = int(pos[0] - im.shape[0] / 2)
        xr = xl + im.shape[0]

        yb = int(pos[1] - im.shape[1] / 2)
        yt = yb + im.shape[1]

        scatter_image[xl:xr, yb:yt, :] = im
    return scatter_image
1019085
def setImageMode(self):
        
        if self._version_server == 3.889:
            self.setPixelFormat(
                    bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
                    redmax = 31, greenmax = 63, bluemax = 31,
                    redshift = 11, greenshift = 5, blueshift = 0
                    )
            self.image_mode = "BGR;16"
        elif (self.truecolor and (not self.bigendian) and self.depth == 24
                and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):

            pixel = ["X"] * self.bypp
            offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
            for offset, color in zip(offsets, "RGB"):
                pixel[offset] = color
            self.image_mode = "".join(pixel)
        else:
            self.setPixelFormat()