Python PIL.ImageOps.fit() Examples

The following are 27 code examples of PIL.ImageOps.fit(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.ImageOps , or try the search function .
Example #1
Source File: upload.py    From zulip with Apache License 2.0 6 votes vote down vote up
def resize_gif(im: GifImageFile, size: int=DEFAULT_EMOJI_SIZE) -> bytes:
    frames = []
    duration_info = []
    # If 'loop' info is not set then loop for infinite number of times.
    loop = im.info.get("loop", 0)
    for frame_num in range(0, im.n_frames):
        im.seek(frame_num)
        new_frame = Image.new("RGBA", im.size)
        new_frame.paste(im, (0, 0), im.convert("RGBA"))
        new_frame = ImageOps.fit(new_frame, (size, size), Image.ANTIALIAS)
        frames.append(new_frame)
        duration_info.append(im.info['duration'])
    out = io.BytesIO()
    frames[0].save(out, save_all=True, optimize=True,
                   format="GIF", append_images=frames[1:],
                   duration=duration_info,
                   loop=loop)
    return out.getvalue() 
Example #2
Source File: download.py    From wallpaper-reddit with GNU General Public License v3.0 6 votes vote down vote up
def download_image(url, title):
    uaurl = request.Request(url, headers={'User-Agent': 'wallpaper-reddit python script by /u/MarcusTheGreat7'})
    f = request.urlopen(uaurl)
    print("downloading " + url)
    try:
        img = Image.open(f).convert('RGB')
        if config.resize:
            config.log("resizing the downloaded wallpaper")
            img = ImageOps.fit(img, (config.minwidth, config.minheight), Image.ANTIALIAS)
        if config.settitle:
            img = set_image_title(img, title)
        if config.opsys == "Windows":
            img.save(config.walldir + '\\wallpaper.bmp', "BMP")
        else:
            img.save(config.walldir + '/wallpaper.jpg', "JPEG")

    except IOError:
        print("Error saving image!")
        sys.exit(1)


# in - string, string - path of the image to set title on, title for image 
Example #3
Source File: notsobot.py    From Trusty-cogs with MIT License 6 votes vote down vote up
def generate_ascii(self, image):
        font = ImageFont.truetype(str(cog_data_path(self)) + "/FreeMonoBold.ttf", 15)
        image_width, image_height = image.size
        aalib_screen_width = int(image_width / 24.9) * 10
        aalib_screen_height = int(image_height / 41.39) * 10
        screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height)

        im = image.convert("L").resize(screen.virtual_size)
        screen.put_image((0, 0), im)
        y = 0
        how_many_rows = len(screen.render().splitlines())
        new_img_width, font_size = font.getsize(screen.render().splitlines()[0])
        img = Image.new("RGBA", (new_img_width, how_many_rows * 15), (255, 255, 255))
        draw = ImageDraw.Draw(img)
        for lines in screen.render().splitlines():
            draw.text((0, y), lines, (0, 0, 0), font=font)
            y += 15
        imagefit = ImageOps.fit(img, (image_width, image_height), Image.ANTIALIAS)
        return imagefit 
Example #4
Source File: wallpaper_merger.py    From HydraPaper with GNU General Public License v3.0 6 votes vote down vote up
def multi_setup_pillow(monitors, save_path, wp_setter_func=None):
    images = list(map(Image.open, [m.wallpaper for m in monitors]))
    resolutions = [(m.width * m.scaling, m.height * m.scaling) for m in monitors]
    offsets = [(m.offset_x, m.offset_y) for m in monitors]

    # DEBUG
    # for m in monitors:
    #     print(m)

    final_image_width = max([m.offset_x + m.width * m.scaling for m in monitors])
    final_image_height = max([m.offset_y + m.height * m.scaling for m in monitors])

    # DEBUG
    # print('Final Size: {} x {}'.format(final_image_width, final_image_height))

    n_images = []
    for i, r in zip(images, resolutions):
        n_images.append(fit(i, r, method=Image.LANCZOS))
    final_image = Image.new('RGB', (final_image_width, final_image_height))
    for i, o in zip(n_images, offsets):
        final_image.paste(i, o)
    final_image.save(save_path) 
Example #5
Source File: strike_utils.py    From strike-with-a-pose with GNU General Public License v3.0 6 votes vote down vote up
def forward(self, input_image):
        (width, height) = (self.width, self.height)

        # Resize image to work with neural network.
        if height < input_image.height < input_image.width:
            new_height = height
            new_width = new_height * input_image.width // input_image.height
        else:
            new_width = width
            new_height = new_width * input_image.height // input_image.width

        image = input_image.resize((new_width, new_height), Image.ANTIALIAS)
        image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)

        # Generate predictions.
        image_tensor = torch.Tensor(np.array(image) / 255.0)
        input_image = image_tensor.permute(2, 0, 1)
        image_normalized = self.preprocess(input_image)
        out = self.net(image_normalized[None, :, :, :].to(self.device))
        return out 
Example #6
Source File: train.py    From StegaStamp with MIT License 6 votes vote down vote up
def get_img_batch(files_list,
                  secret_size,
                  batch_size=4,
                  size=(400,400)):

    batch_cover = []
    batch_secret = []

    for i in range(batch_size):
        img_cover_path = random.choice(files_list)
        try:
            img_cover = Image.open(img_cover_path).convert("RGB")
            img_cover = ImageOps.fit(img_cover, size)
            img_cover = np.array(img_cover, dtype=np.float32) / 255.
        except:
            img_cover = np.zeros((size[0],size[1],3), dtype=np.float32)
        batch_cover.append(img_cover)

        secret = np.random.binomial(1, .5, secret_size)
        batch_secret.append(secret)

    batch_cover, batch_secret = np.array(batch_cover), np.array(batch_secret)
    return batch_cover, batch_secret 
Example #7
Source File: utils.py    From stanford-tensorflow-tutorials with MIT License 5 votes vote down vote up
def get_resized_image(img_path, height, width, save=True):
    image = Image.open(img_path)
    # it's because PIL is column major so you have to change place of width and height
    # this is stupid, i know
    image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
    if save:
        image_dirs = img_path.split('/')
        image_dirs[-1] = 'resized_' + image_dirs[-1]
        out_path = '/'.join(image_dirs)
        if not os.path.exists(out_path):
            image.save(out_path)
    image = np.asarray(image, np.float32)
    return np.expand_dims(image, 0) 
Example #8
Source File: simpleassetsmanager.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save(self, data, file_id=None, metadata={}, THUMB_SIZE=()):
        if file_id is None:
            file_id = unicode(uuid.uuid4())
        with open(self._get_filename(file_id), "w") as f:
            f.write(data)
        # Store metadata
        with open(self._get_metadata_filename(file_id), "w") as f:
            f.write(json.dumps(metadata))

        img = None
        try:
            img = Image.open(self._get_filename(file_id))
        except IOError:
            log.info('Not an image file, skipping medium & thumbnail generation')
        else:
            # Store thumbnail & medium
            kw = {}
            if 'transparency' in img.info:
                kw['transparency'] = img.info["transparency"]

            orig_width, orig_height = img.size

            medium_size = self.MEDIUM_WIDTH, int(float(self.MEDIUM_WIDTH) * orig_height / orig_width)
            medium = img.copy()

            medium.thumbnail(medium_size, Image.ANTIALIAS)
            medium.save(self._get_filename(file_id, 'medium'), img.format, quality=75, **kw)  # 'JPEG')

            thumb = ImageOps.fit(img, THUMB_SIZE if THUMB_SIZE else self.THUMB_SIZE, Image.ANTIALIAS)
            thumb.save(self._get_filename(file_id, 'thumb'), img.format, quality=75, **kw)  # 'JPEG')
        return file_id 
Example #9
Source File: utils.py    From stanford-tensorflow-tutorials with MIT License 5 votes vote down vote up
def get_resized_image(img_path, height, width, save=True):
    image = Image.open(img_path)
    # it's because PIL is column major so you have to change place of width and height
    # this is stupid, i know
    image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
    if save:
        image_dirs = img_path.split('/')
        image_dirs[-1] = 'resized_' + image_dirs[-1]
        out_path = '/'.join(image_dirs)
        if not os.path.exists(out_path):
            image.save(out_path)
    image = np.asarray(image, np.float32)
    return np.expand_dims(image, 0) 
Example #10
Source File: utils.py    From stanford-tensorflow-tutorials with MIT License 5 votes vote down vote up
def get_resized_image(img_path, width, height, save=True):
    image = Image.open(img_path)
    # PIL is column major so you have to swap the places of width and height
    image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
    if save:
        image_dirs = img_path.split('/')
        image_dirs[-1] = 'resized_' + image_dirs[-1]
        out_path = '/'.join(image_dirs)
        if not os.path.exists(out_path):
            image.save(out_path)
    image = np.asarray(image, np.float32)
    return np.expand_dims(image, 0) 
Example #11
Source File: thumbnail_processors.py    From astrobin with GNU Affero General Public License v3.0 5 votes vote down vote up
def rounded_corners(image, rounded=False, **kwargs):
    if rounded:
        mask = Image.open('astrobin/thumbnail-mask.png').convert('L')
        mask = mask.resize(image.size, Image.ANTIALIAS)
        image = ImageOps.fit(image, mask.size, centering=(0.5, 0.5))
        image.putalpha(mask)

    return image 
Example #12
Source File: flask_admin_s3_upload.py    From flask-admin-s3-upload with Apache License 2.0 5 votes vote down vote up
def _resize(self, image, size):
        (width, height, force) = size

        if image.size[0] > width or image.size[1] > height:
            if force:
                return ImageOps.fit(self.image, (width, height),
                                    Image.ANTIALIAS)
            else:
                thumb = self.image.copy()
                thumb.thumbnail((width, height), Image.ANTIALIAS)
                return thumb

        return image 
Example #13
Source File: classify.py    From DevOps-For-AI-Apps with MIT License 5 votes vote down vote up
def resize(img_file, new_size=(100, 100)):
    return ImageOps.fit(img_file, new_size, Image.ANTIALIAS) 
Example #14
Source File: data_dirs_organizer.py    From painters with MIT License 5 votes vote down vote up
def _save_scaled_cropped_img(src, dest):
    image = load_img(src)
    image = fit(image, IMGS_DIM_2D, method=LANCZOS)
    image.save(dest)
    return image 
Example #15
Source File: not_hotdog_model.py    From hotdog-not-hotdog with MIT License 5 votes vote down vote up
def image_to_tensor(pil_image):
    #resize image
    resized=ImageOps.fit(pil_image, imgsize, Image.ANTIALIAS)
    # transform it into a torch tensor
    loader = transforms.Compose([
        transforms.ToTensor()])
    return loader(resized).unsqueeze(0) #need to add one dimension, need to be 4D to pass into the network

#load model 
Example #16
Source File: resize_imgs.py    From DCGAN-Keras with MIT License 5 votes vote down vote up
def resize_imgs(self, path):
        for i, img_path in enumerate(glob.glob(path)):
            print(i, img_path)
            img = Image.open(img_path)
            img = ImageOps.fit(img, (self.img_size[0], self.img_size[1]), Image.ANTIALIAS)
            name = img_path.split("\\")[-1].split('.')[0]
            if not os.path.exists(f"resized_{self.img_size[0]}_{self.img_size[1]}"):
                os.makedirs(f"resized_{self.img_size[0]}_{self.img_size[1]}")
            img.save(f"resized_{self.img_size[0]}_{self.img_size[1]}/{name}.png") 
Example #17
Source File: object_detection.py    From aiexamples with Apache License 2.0 5 votes vote down vote up
def download_and_resize_image(url, new_width=256, new_height=256,
                              display=False):
  _, filename = tempfile.mkstemp(suffix=".jpg")
  response = urlopen(url)
  image_data = response.read()
  image_data = BytesIO(image_data)
  pil_image = Image.open(image_data)
  pil_image = ImageOps.fit(pil_image, (new_width, new_height), Image.ANTIALIAS)
  pil_image_rgb = pil_image.convert("RGB")
  pil_image_rgb.save(filename, format="JPEG", quality=90)
  print("Image downloaded to %s." % filename)
  if display:
    display_image(pil_image)
  return filename 
Example #18
Source File: versatileimagefield.py    From django-versatileimagefield with MIT License 5 votes vote down vote up
def process_image(self, image, image_format, save_kwargs,
                      width, height):
        """
        Return a BytesIO instance of `image` cropped to `width` and `height`.

        Cropping will first reduce an image down to its longest side
        and then crop inwards centered on the Primary Point of Interest
        (as specified by `self.ppoi`)
        """
        imagefile = BytesIO()
        palette = image.getpalette()
        cropped_image = self.crop_on_centerpoint(
            image,
            width,
            height,
            self.ppoi
        )

        # Using ImageOps.fit on GIFs can introduce issues with their palette
        # Solution derived from: http://stackoverflow.com/a/4905209/1149774
        if image_format == 'GIF':
            cropped_image.putpalette(palette)

        cropped_image.save(
            imagefile,
            **save_kwargs
        )

        return imagefile 
Example #19
Source File: test_imageops.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_1pxfit(self):
        # Division by zero in equalize if image is 1 pixel high
        newimg = ImageOps.fit(hopper("RGB").resize((1, 1)), (35, 35))
        self.assertEqual(newimg.size, (35, 35))

        newimg = ImageOps.fit(hopper("RGB").resize((1, 100)), (35, 35))
        self.assertEqual(newimg.size, (35, 35))

        newimg = ImageOps.fit(hopper("RGB").resize((100, 1)), (35, 35))
        self.assertEqual(newimg.size, (35, 35)) 
Example #20
Source File: upload.py    From zulip with Apache License 2.0 5 votes vote down vote up
def resize_emoji(image_data: bytes, size: int=DEFAULT_EMOJI_SIZE) -> bytes:
    try:
        im = Image.open(io.BytesIO(image_data))
        image_format = im.format
        if image_format == "GIF":
            # There are a number of bugs in Pillow.GifImagePlugin which cause
            # results in resized gifs being broken. To work around this we
            # only resize under certain conditions to minimize the chance of
            # creating ugly gifs.
            should_resize = any((
                im.size[0] != im.size[1],                            # not square
                im.size[0] > MAX_EMOJI_GIF_SIZE,                     # dimensions too large
                len(image_data) > MAX_EMOJI_GIF_FILE_SIZE_BYTES,     # filesize too large
            ))
            return resize_gif(im, size) if should_resize else image_data
        else:
            im = exif_rotate(im)
            im = ImageOps.fit(im, (size, size), Image.ANTIALIAS)
            out = io.BytesIO()
            im.save(out, format=image_format)
            return out.getvalue()
    except OSError:
        raise BadImageError(_("Could not decode image; did you upload an image file?"))
    except DecompressionBombError:
        raise BadImageError(_("Image size exceeds limit."))


### Common 
Example #21
Source File: upload.py    From zulip with Apache License 2.0 5 votes vote down vote up
def resize_avatar(image_data: bytes, size: int=DEFAULT_AVATAR_SIZE) -> bytes:
    try:
        im = Image.open(io.BytesIO(image_data))
        im = exif_rotate(im)
        im = ImageOps.fit(im, (size, size), Image.ANTIALIAS)
    except OSError:
        raise BadImageError(_("Could not decode image; did you upload an image file?"))
    except DecompressionBombError:
        raise BadImageError(_("Image size exceeds limit."))
    out = io.BytesIO()
    if im.mode == 'CMYK':
        im = im.convert('RGB')
    im.save(out, format='png')
    return out.getvalue() 
Example #22
Source File: thumbnails.py    From photonix with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_thumbnail(photo, width=256, height=256, crop='cover', quality=75, return_type='path', force_regenerate=False):
    if not isinstance(photo, Photo):
        photo = Photo.objects.get(id=photo)

    # If thumbnail image was previously generated and we weren't told to re-generate, return that one
    output_path = get_thumbnail_path(photo, width, height, crop, quality)
    if os.path.exists(output_path):
        if return_type == 'bytes':
            return open(output_path, 'rb').read()
        else:
            return output_path

    # Read base image and metadata
    input_path = photo.base_image_path
    im = Image.open(input_path)

    if im.mode != 'RGB':
        im = im.convert('RGB')

    metadata = PhotoMetadata(input_path)

    # Perform rotations if decalared in metadata
    if metadata.get('Orientation') in ['Rotate 90 CW', 'Rotate 270 CCW']:
        im = im.rotate(-90, expand=True)
    elif metadata.get('Orientation') in ['Rotate 90 CCW', 'Rotate 270 CW']:
        im = im.rotate(90, expand=True)

    # Crop / resize
    if crop == 'cover':
        im = ImageOps.fit(im, (width, height), Image.ANTIALIAS)
    else:
        im.thumbnail((width, height), Image.ANTIALIAS)

    # Save to disk (keeping the bytes in memory if we need to return them)
    if return_type == 'bytes':
        img_byte_array = io.BytesIO()
        im.save(img_byte_array, format='JPEG', quality=quality)
        with open(output_path, 'wb') as f:
            f.write(img_byte_array.getvalue())
    else:
        im.save(output_path, format='JPEG', quality=quality)

    # Update Photo DB model
    photo.last_thumbnailed_version = 0
    photo.last_thumbnailed_at = timezone.now()
    photo.save()

    # Return accordingly
    if return_type == 'bytes':
        return img_byte_array.getvalue()
    return output_path 
Example #23
Source File: decode_image.py    From StegaStamp with MIT License 4 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('model', type=str)
    parser.add_argument('--image', type=str, default=None)
    parser.add_argument('--images_dir', type=str, default=None)
    parser.add_argument('--secret_size', type=int, default=100)
    args = parser.parse_args()

    if args.image is not None:
        files_list = [args.image]
    elif args.images_dir is not None:
        files_list = glob.glob(args.images_dir + '/*')
    else:
        print('Missing input image')
        return

    sess = tf.InteractiveSession(graph=tf.Graph())

    model = tf.saved_model.loader.load(sess, [tag_constants.SERVING], args.model)

    input_image_name = model.signature_def[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY].inputs['image'].name
    input_image = tf.get_default_graph().get_tensor_by_name(input_image_name)

    output_secret_name = model.signature_def[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY].outputs['decoded'].name
    output_secret = tf.get_default_graph().get_tensor_by_name(output_secret_name)

    bch = bchlib.BCH(BCH_POLYNOMIAL, BCH_BITS)

    for filename in files_list:
        image = Image.open(filename).convert("RGB")
        image = np.array(ImageOps.fit(image,(400, 400)),dtype=np.float32)
        image /= 255.

        feed_dict = {input_image:[image]}

        secret = sess.run([output_secret],feed_dict=feed_dict)[0][0]

        packet_binary = "".join([str(int(bit)) for bit in secret[:96]])
        packet = bytes(int(packet_binary[i : i + 8], 2) for i in range(0, len(packet_binary), 8))
        packet = bytearray(packet)

        data, ecc = packet[:-bch.ecc_bytes], packet[-bch.ecc_bytes:]

        bitflips = bch.decode_inplace(data, ecc)

        if bitflips != -1:
            try:
                code = data.decode("utf-8")
                print(filename, code)
                continue
            except:
                continue
        print(filename, 'Failed to decode') 
Example #24
Source File: driver.py    From DevOps-For-AI-Apps with MIT License 4 votes vote down vote up
def run(inputString):
    """ Classify the input using the loaded model
    """
    start = t.default_timer()

    images = json.loads(inputString)
    result = []
    totalPreprocessTime = 0
    totalEvalTime = 0
    totalResultPrepTime = 0

    for base64ImgString in images:
        if base64ImgString.startswith('b\''):
            base64ImgString = base64ImgString[2:-1]
        base64Img = base64ImgString.encode('utf-8')

        # Preprocess the input data
        startPreprocess = t.default_timer()
        decoded_img = base64.b64decode(base64Img)
        img_buffer = BytesIO(decoded_img)

        # Load image with PIL (RGB)
        pil_img = Image.open(img_buffer).convert('RGB')
        pil_img = ImageOps.fit(pil_img, (224, 224), Image.ANTIALIAS)
        rgb_image = np.array(pil_img, dtype=np.float32)

        # Resnet trained with BGR
        bgr_image = rgb_image[..., [2, 1, 0]]
        imageData = np.ascontiguousarray(np.rollaxis(bgr_image, 2))

        endPreprocess = t.default_timer()
        totalPreprocessTime += endPreprocess - startPreprocess

        # Evaluate the model using the input data
        startEval = t.default_timer()
        imgPredictions = np.squeeze(trainedModel.eval({trainedModel.arguments[0]: [imageData]}))
        endEval = t.default_timer()
        totalEvalTime += endEval - startEval

        # Only return top 3 predictions
        startResultPrep = t.default_timer()
        resultIndices = (-np.array(imgPredictions)).argsort()[:topResult]
        imgTopPredictions = []
        for i in range(topResult):
            imgTopPredictions.append((labelLookup[resultIndices[i]], imgPredictions[resultIndices[i]] * 100))
        endResultPrep = t.default_timer()
        result.append(imgTopPredictions)

        totalResultPrepTime += endResultPrep - startResultPrep

    end = t.default_timer()

    logger.info("Predictions: {0}".format(result))
    logger.info("Predictions took {0} ms".format(round((end - start) * 1000, 2)))
    logger.info("Time distribution: preprocess={0} ms, eval={1} ms, resultPrep = {2} ms".format(
        round(totalPreprocessTime * 1000, 2), round(totalEvalTime * 1000, 2), round(totalResultPrepTime * 1000, 2)))

    actualWorkTime = round((totalPreprocessTime + totalEvalTime + totalResultPrepTime) * 1000, 2)
    return (result, 'Computed in {0} ms'.format(actualWorkTime)) 
Example #25
Source File: cropall.py    From cropall with GNU General Public License v3.0 4 votes vote down vote up
def update_preview(self, widget):
		if self.item:
			#get a crop for the preview
			#box = tuple((int(round(v)) for v in widget.coords(self.item)))
			box = self.getRealBox()
			pbox = self.getPreviewBox()
			if fast_preview:
				preview = self.image.crop(pbox) # region of interest
			else:
				preview = self.imageOrig.crop(box) # region of interest

			#add black borders for correct aspect ratio
			#if preview.size[0] > 512:
			preview.thumbnail(self.image.size, Image.ANTIALIAS) #downscale to preview rez
			paspect = preview.size[0]/float(preview.size[1])
			aspect = self.image.size[0]/float(self.image.size[1])
			if paspect < aspect:
				bbox = (0, 0, int(preview.size[1] * aspect), preview.size[1])
			else:
				bbox = (0, 0, preview.size[0], int(preview.size[0] / aspect))
			preview = ImageOps.expand(preview, border=((bbox[2]-preview.size[0])//2, (bbox[3]-preview.size[1])//2))
			#preview = ImageOps.fit(preview, size=self.image.size, method=Image.ANTIALIAS, bleed=-10.0)

			#resize to preview rez (if too small)
			self.preview = preview.resize(self.image.size, Image.ANTIALIAS)
			self.previewPhoto = ImageTk.PhotoImage(self.preview)
			self.previewLabel.configure(image=self.previewPhoto)

			print str(box[2]-box[0])+"x"+str(box[3]-box[1])+"+"+str(box[0])+"+"+str(box[1]) 
Example #26
Source File: cropall.py    From cropall with GNU General Public License v3.0 4 votes vote down vote up
def getRealBox(self):
		imw = self.imageOrigSize[0]
		imh = self.imageOrigSize[1]
		prevw = self.imagePhoto.width()
		prevh = self.imagePhoto.height()

		if (self.selection_mode.get() == 'click-drag'):
			top_left = (self.selection_tl_x*imw/prevw, self.selection_tl_y*imh/prevh)
			top_left = (max(top_left[0], 0), max(top_left[1], 0))
			bottom_right = (self.selection_br_x*imw/prevw, self.selection_br_y*imh/prevh)
			bottom_right = (max(top_left[0] + 1, min(bottom_right[0], imw)), max(top_left[1] + 1, min(bottom_right[1], imh)))
			w = bottom_right[0] - top_left[0]
			h = bottom_right[1] - top_left[1]

			# increase box to cover the selection, matching the aspect ratio
			if (self.restrictRatio.get() == 1):
				if (float(w)/float(h) > self.aspectRatio): # box is too wide -> increase height to match aspect
					h = w / self.aspectRatio
					if self.mouse_move_coord[1] > self.mouse_down_coord[1]:
						bottom_right = (bottom_right[0], top_left[1] + h)
					else:
						top_left = (top_left[0], bottom_right[1] - h)
				else: # box is too tall -> increase width to match aspect
					w = h * self.aspectRatio
					if self.mouse_move_coord[0] > self.mouse_down_coord[0]:
						bottom_right = (top_left[0] + w, bottom_right[1])
					else:
						top_left = (bottom_right[0] - w, top_left[1])

			"""
			# reduce box to fit within selection, matching the aspect ratio
			if (self.restrictRatio.get() == 1):
				if (float(w)/float(h) > self.aspectRatio): # box is too wide -> reduce width to match aspect
					w = h * self.aspectRatio
					if self.mouse_move_coord[0] > self.mouse_down_coord[0]:
						bottom_right = (top_left[0] + w, bottom_right[1])
					else:
						top_left = (bottom_right[0] - w, top_left[1])
				else: # box is too tall -> reduce height to match aspect
					h = w / self.aspectRatio
					if self.mouse_move_coord[1] > self.mouse_down_coord[1]:
						bottom_right = (bottom_right[0], top_left[1] + h)
					else:
						top_left = (top_left[0], bottom_right[1] - h)
			"""

			box = (int(round(top_left[0])), int(round(top_left[1])), int(round(bottom_right[0])), int(round(bottom_right[1])))
		else:
			w, h = self.getCropSize()
			box = (int(round(self.x*imw/prevw))-w//2, int(round(self.y*imh/prevh))-h//2)
			box = (max(box[0], 0), max(box[1], 0))
			box = (min(box[0]+w, imw)-w, min(box[1]+h, imh)-h)
			box = (box[0], box[1], box[0]+w, box[1]+h)

		return box 
Example #27
Source File: test_imageops.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_sanity(self):

        ImageOps.autocontrast(hopper("L"))
        ImageOps.autocontrast(hopper("RGB"))

        ImageOps.autocontrast(hopper("L"), cutoff=10)
        ImageOps.autocontrast(hopper("L"), ignore=[0, 255])

        ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255))
        ImageOps.colorize(hopper("L"), "black", "white")

        ImageOps.pad(hopper("L"), (128, 128))
        ImageOps.pad(hopper("RGB"), (128, 128))

        ImageOps.crop(hopper("L"), 1)
        ImageOps.crop(hopper("RGB"), 1)

        ImageOps.deform(hopper("L"), self.deformer)
        ImageOps.deform(hopper("RGB"), self.deformer)

        ImageOps.equalize(hopper("L"))
        ImageOps.equalize(hopper("RGB"))

        ImageOps.expand(hopper("L"), 1)
        ImageOps.expand(hopper("RGB"), 1)
        ImageOps.expand(hopper("L"), 2, "blue")
        ImageOps.expand(hopper("RGB"), 2, "blue")

        ImageOps.fit(hopper("L"), (128, 128))
        ImageOps.fit(hopper("RGB"), (128, 128))

        ImageOps.flip(hopper("L"))
        ImageOps.flip(hopper("RGB"))

        ImageOps.grayscale(hopper("L"))
        ImageOps.grayscale(hopper("RGB"))

        ImageOps.invert(hopper("L"))
        ImageOps.invert(hopper("RGB"))

        ImageOps.mirror(hopper("L"))
        ImageOps.mirror(hopper("RGB"))

        ImageOps.posterize(hopper("L"), 4)
        ImageOps.posterize(hopper("RGB"), 4)

        ImageOps.solarize(hopper("L"))
        ImageOps.solarize(hopper("RGB"))

        ImageOps.exif_transpose(hopper("L"))
        ImageOps.exif_transpose(hopper("RGB"))