Ejemplo n.º 1
0
    def _load_img(self, run_id, camera, timestamp):
        if self.azure_loader is None:
            # load from local storage
            img_name = os.path.join(self.img_root, run_id, 'cameras', camera,
                                    str(timestamp) + 'unixus.jpeg')
            if os.path.exists(img_name):
                image = pil_loader(img_name)
            else:
                print('skipping missing image: ', img_name)
                image = None
        else:
            image = self.azure_loader(run_id, camera, timestamp)

        # hack for images resized/cropped on disk
        if image is None:
            pass
        elif image.size == (1920, 1200):
            image = image.resize((960, 600))
        elif image.size == (1920, 896):
            image = image.resize((960, 448))
            image = ImageOps.pad(image, (960, 600), centering=(0, 0))
        elif image.size == (960, 448):
            image = ImageOps.pad(image, (960, 600), centering=(0, 0))
        elif image.size == (960, 600):
            pass
        elif image.size == (480, 300):
            image = image.resize((960, 600))
        else:
            print('unknown image size', image.size, img_name)
            image = None

        return image
Ejemplo n.º 2
0
def create_chip_image(amount, font):
    
    image = Image.new("RGBA", SIZE)
    draw = ImageDraw.Draw(image)

    draw.ellipse([(0, 0), SIZE], fill=BACKGROUND_COLOURS[amount])
    
    size = draw.textsize(amount, font=font)
    draw.text(((SIZE[0] - size[0])/2, (SIZE[1] - size[1])/2 + VERTICAL_CORRECTION), str(amount), fill=FOREGROUND_COLOURS[amount], font=font)

    opposite = image.copy()
    image = ImageOps.pad(image, (SIZE[0]*2, SIZE[1]), centering=(0, 0.5))
    opposite = ImageOps.pad(opposite, (SIZE[0]*2, SIZE[1]), centering=(1, 0.5))

    image = Image.alpha_composite(image, opposite)
    image = ImageOps.pad(image, (SIZE[0]*2, SIZE[1]*2), centering=(0.5, 1))
    draw = ImageDraw.Draw(image)

    draw.rectangle([(0, 0), (SIZE[0]*2, SIZE[1])], fill=BACKGROUND_COLOURS[amount])

    side_rect_width = SIZE[0] * 2.0 / NUM_SIDE_RECTS
    side_rect_height = SIZE[1] / 2.0

    for i in range(NUM_SIDE_RECTS):
        side_rect_x = side_rect_width * i
        side_rect_y = 0
        if i % 2 != 0:
            side_rect_y = side_rect_height

        draw.rectangle([(side_rect_x, side_rect_y), (side_rect_x + side_rect_width, side_rect_y + side_rect_height)], fill=FOREGROUND_COLOURS[amount])

    image.save(amount + ".png")
Ejemplo n.º 3
0
def test_sanity():

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

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

    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.contain(hopper("L"), (128, 128))
    ImageOps.contain(hopper("RGB"), (128, 128))

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

    ImageOps.deform(hopper("L"), deformer)
    ImageOps.deform(hopper("RGB"), 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("1"))
    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"))
Ejemplo n.º 4
0
    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"))
Ejemplo n.º 5
0
    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"))
Ejemplo n.º 6
0
def pad_imgs_words(dataset_dir: str, max_word_size=MAX_WORD_SIZE):
    for img_word_file_path, img_word in for_each_img_word(dataset_dir):
        new_img = ImageOps.pad(img_word.convert("RGB"),
                               size=max_word_size,
                               color=(0xFF, 0xFF, 0xFF))
        img_word.close()
        new_img.save(img_word_file_path)
Ejemplo n.º 7
0
    def convert_image(self, image):
        orig_width, orig_height = image.size

        # transparent to white
        image = image.convert('RGBA')
        background = Image.new('RGBA', image.size, (255, 255, 255))
        background.paste(image, (0, 0), image)
        image = background.convert('RGB')

        # trim white
        background = Image.new('RGB', image.size, (255, 255, 255))
        diff = ImageChops.difference(image, background)
        diff = ImageChops.add(diff, diff, 2.0, -100)
        image = image.crop(diff.getbbox())

        # make it a square
        side_size = max(image.width, image.height)
        image = ImageOps.pad(image, (side_size, side_size),
                             color=(255, 255, 255))

        # resize
        image = image.resize((self.size_px, self.size_px))

        # save, put information about the original width and height to EXIF
        buffer = BytesIO()
        image.save(buffer,
                   'PNG',
                   exif=create_orig_size_exif(orig_width, orig_height))
        return image, buffer
Ejemplo n.º 8
0
def build_lines_train_dataset_img(imgs_dir: str,
                                  img_num: int,
                                  max_line_h=MAX_LINE_H):
    print('building lines of train dataset image num {}'.format(img_num))

    train_dir = get_train_dir(imgs_dir)

    line_info = load_img_lines_info(img_num=img_num)
    y_positions = parse_y_positions(line_info)
    top_test_area = line_info['top_test_area'].flatten()[0]
    bottom_test_area = line_info['bottom_test_area'].flatten()[0]
    img = load_img(dir=imgs_dir, img_num=img_num)

    sub_img_dir = join(train_dir, str(img_num))
    Path(sub_img_dir).mkdir(parents=True, exist_ok=True)

    for idx in range(len(y_positions) - 1):
        if y_positions[
                idx +
                1] < top_test_area or y_positions[idx] > bottom_test_area:
            sub_img = img.crop(box=(0, y_positions[idx], ORIGINAL_IMG_W,
                                    y_positions[idx + 1]))
            file_name = '{0}_{1}.jpg'.format(img_num, idx + 1)
            sub_img_file_path = join(sub_img_dir, file_name)
            new_img = ImageOps.pad(sub_img.convert("RGB"),
                                   size=(ORIGINAL_IMG_W, max_line_h),
                                   color=(0xFF, 0xFF, 0xFF))
            if not is_white_img(new_img):
                new_img.save(sub_img_file_path)
Ejemplo n.º 9
0
def resize_gif(im: GifImageFile, size: int = DEFAULT_EMOJI_SIZE) -> bytes:
    frames = []
    duration_info = []
    disposals = []
    # 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 = im.copy()
        new_frame.paste(im, (0, 0), im.convert("RGBA"))
        new_frame = ImageOps.pad(new_frame, (size, size), Image.ANTIALIAS)
        frames.append(new_frame)
        duration_info.append(im.info["duration"])
        disposals.append(im.disposal_method)
    out = io.BytesIO()
    frames[0].save(
        out,
        save_all=True,
        optimize=False,
        format="GIF",
        append_images=frames[1:],
        duration=duration_info,
        disposal=disposals,
        loop=loop,
    )
    return out.getvalue()
Ejemplo n.º 10
0
    def add_sizes(self, sizes: Iterable[Tuple[int, int]]):
        """
        Add specified sizes to this cursor, by resizing cursors which already exist in this CursorIcon...

        :param sizes: An iterable of tuples of 2 integers, representing width-height pairs to be added as sizes to
                      this cursor.
        """
        if(len(self) == 0):
            raise ValueError("Cursor is empty!!! Can't add sizes!!!")

        max_size = self.max_size()

        for size in sizes:
            if(size not in self):
                x_ratio, y_ratio = size[0] / max_size[0], size[1] / max_size[1]

                if(x_ratio <= y_ratio):
                    final_img_w = size[0]
                    w_offset = 0
                    final_img_h = (max_size[1] / max_size[0]) * final_img_w
                    h_offset = (size[1] - final_img_h) / 2
                else:
                    final_img_h = size[1]
                    h_offset = 0
                    final_img_w = (max_size[0] / max_size[1]) * final_img_h
                    w_offset = (size[0] - final_img_w) / 2

                new_cur = ImageOps.pad(self[max_size].image, size, Image.LANCZOS).resize(size, Image.LANCZOS)

                new_hx = w_offset + (self[max_size].hotspot[0] / max_size[0]) * final_img_w
                new_hy = h_offset + (self[max_size].hotspot[1] / max_size[1]) * final_img_h
                self.add(CursorIcon(new_cur, int(new_hx), int(new_hy)))
	def view_all(self, dim_x, dim_y, ind, save = False, save_dir = None, save_name = None):
		img_dim_x, img_dim_y = numpy.shape(self.input_imgs[ind])[0], numpy.shape(self.input_imgs[ind])[1]
		total_width, total_height = dim_y * img_dim_y, dim_x * img_dim_x 

		header_heights = [0.5, 0.4, 0.3, 0.4, 0.3]
		header_text = ['Input Image', 'True Depths', 'Predicted Depths', 'True Masks', 'Predicted_masks']
		headers = [Image.new('F', (total_width, int(total_height * fac)), 225.) for fac in header_heights]

		draws = [ImageDraw.Draw(img) for img in headers]
		for i in xrange(len(headers)):
			draws[i].text((total_width * 0.35, total_height * header_heights[i] * 0.35), header_text[i]) 

		input_img = Image.fromarray(self.input_imgs[ind])
		input_img = input_img.rotate(90)
		input_img = input_img.resize((dim_x * img_dim_x, total_height))
		input_img = ImageOps.pad(input_img, (total_width, total_height))

		true_i = self.shape_image(self.true_imgs[ind], dim_x, dim_y)
		true_m = self.shape_image(self.true_masks[ind], dim_x, dim_y)
		pred_i = self.shape_image(self.pred_imgs[ind], dim_x, dim_y)
		pred_m = self.shape_image(self.pred_masks[ind], dim_x, dim_y)
		data = numpy.vstack([headers[0], numpy.array(input_img) * 255., headers[1], true_i * 255., headers[2], pred_i * 255., headers[3], true_m * 255., headers[4], pred_m * 255.])
		
		if save == False:
			img = Image.fromarray(data)	
			img.show()
		else:
			img = Image.fromarray(data)
			img.convert('L').save(os.path.join(save_dir, str(save_name)+".PNG"))
Ejemplo n.º 12
0
def load_and_modify_image(path):
    img = Image.open(path).convert(
        mode='RGB')  #открывается изображение, приводится к rgb формату
    img = ImageOps.pad(
        img, (W, H)
    )  #изменяет размер изображения в соответствии с заданными измерениями
    return img  #возвращает преобразованное изображение
Ejemplo n.º 13
0
def image_proccessing(path_to_image: str) -> None:
  try:
    image = Image.open(path_to_image)
  except IOError:
    print("Cant open image!")
    sys.exit(1)

  original_name = path_to_image.split(os.sep)[-1].split('.')[-2]
  original_extension = path_to_image.split(os.sep)[-1].split('.')[-1]

  print('Opened: {}'.format(original_name + '.' + original_extension))

  original_width, original_height = image.size
  new_width = 0
  new_height = 0

  print('Original size: {0}x{1}'.format(original_width, original_height))

  if (
    round(
      original_width / original_height,
      1
    ) not in [
      0.8,
      1.2
    ]
  ) == True:
    if (original_height >= original_width):
      new_width = int(original_width * (4/5))
      new_height = original_height
    else:
      new_width = original_width
      new_height = int(original_height * (5/4))

    print('New size: {0}x{1}'.format(new_width, new_height))

    image = ImageOps.pad(
      image=image,
      size=(new_width, new_height),
      method=Image.BICUBIC,
      color=0x00FFFFFF,
      centering=(0, 0.5)
    )

    splitted_path_to_image = path_to_image.split(os.sep)
    splitted_path_to_image[-1] = original_name + '_4x5.' + original_extension

    new_path_to_image = os.sep.join(splitted_path_to_image)

    try:
      image.save(new_path_to_image)
    except IOError:
      print("Can't save image")
      sys.exit(1)

    print('Saved as: ', new_path_to_image)
  else:
    print('The image does not need to be resized! Skip...')

  print('\n')
Ejemplo n.º 14
0
def save_as_ig_square(path):
    with Image.open(path) as image:
        side_px = max(image.width, image.height)
        image = ImageOps.pad(image, (side_px, side_px), color=(0, 0, 0))
        path = path.with_name(f"{path.stem}-ig{path.suffix}")
        image.save(path, 'PNG')
        return path
Ejemplo n.º 15
0
 def preload(self):
     image = Image.open(self._gif_files[self._index])
     print("Loading {}...".format(self._gif_files[self._index]))
     if "duration" in image.info:
         self._duration = image.info["duration"]
     else:
         self._duration = 0
     if "loop" in image.info:
         self._loop = image.info["loop"]
     else:
         self._loop = 1
     self._frame_count = image.n_frames
     self._frames.clear()
     for frame in range(self._frame_count):
         image.seek(frame)
         # Create blank image for drawing.
         # Make sure to create image with mode 'RGB' for full color.
         frame_object = Frame(duration=self._duration)
         if "duration" in image.info:
             frame_object.duration = image.info["duration"]
         frame_object.image = ImageOps.pad(  # pylint: disable=no-member
             image.convert("RGB"),
             (self._width, self._height),
             method=Image.NEAREST,
             color=(0, 0, 0),
             centering=(0.5, 0.5),
         )
         self._frames.append(frame_object)
Ejemplo n.º 16
0
def pad_image(update: 'telegram.Update',
              context: 'telegram.ext.CallbackContext') -> None:
    """Pad images to 1:1 for use in profile pictures"""
    if update.message:
        message: 'telegram.Message' = update.message
    else:
        return

    if not (message.reply_to_message and message.reply_to_message.photo):
        message.reply_text(
            text="*Usage:* \nReply to a photo with `/pfp {COLOR}`\n"
            "*Example:* `/pfp #AA33FF`\n"
            "You can also specify a hex color value. Defaults to black if none provided."
        )
    else:
        pic: telegram.PhotoSize = message.reply_to_message.photo[-1]

        size: Tuple[int, int] = (max(pic.width,
                                     pic.height), max(pic.width, pic.height))
        color: str = ''.join(context.args) if context.args else 'black'

        with BytesIO(pic.get_file().download_as_bytearray()
                     ) as pic_file, BytesIO() as dp:
            try:
                padded_image = ImageOps.pad(image=Image.open(pic_file),
                                            size=size,
                                            color=color)
                padded_image.save(dp, 'JPEG')
                dp.seek(0)

                message.reply_photo(photo=dp)
            except ValueError:
                message.reply_text(text="Invalid color")
Ejemplo n.º 17
0
Archivo: pfp.py Proyecto: Tyagdit/bot
def pad_image(update, context):
    """Pad images to 1:1 for use in profile pictures"""

    message = update.message

    if not message.reply_to_message or not message.reply_to_message.photo:
        message.reply_text("*Usage:* \nReply to a photo with `/pfp {COLOR}`\n"
                           "*Example:* `/pfp red`\n"
                           "Defaults to black if none provided")

    else:
        pic = message.reply_to_message.photo[-1]
        size = (max(pic.width, pic.height), max(pic.width, pic.height))
        color = ''.join(context.args)
        color = color if color in colormap else "black"

        with BytesIO(pic.get_file().download_as_bytearray()
                     ) as pic_file, BytesIO() as dp:
            padded_image = ImageOps.pad(image=Image.open(pic_file),
                                        size=size,
                                        color=color)
            padded_image.save(dp, 'JPEG')

            dp.seek(0)
            message.reply_photo(photo=dp, quote=True)
Ejemplo n.º 18
0
def padImage(input_png,
             output_png,
             screen_width,
             screen_height,
             bezel_width,
             bezel_height,
             bezel_stretch=False):
    fillcolor = 'black'

    wratio = screen_width / float(bezel_width)
    hratio = screen_height / float(bezel_height)

    xoffset = screen_width - bezel_width
    yoffset = screen_height - bezel_height

    borderw = 0
    borderh = 0
    if wratio > 1:
        borderw = xoffset // 2
    if hratio > 1:
        borderh = yoffset // 2
    imgin = Image.open(input_png)
    if imgin.mode != "RGBA":
        alphaPaste(input_png, output_png, imgin, fillcolor,
                   (screen_width, screen_height), bezel_stretch)
    else:
        if bezel_stretch:
            imgout = ImageOps.fit(imgin, (screen_width, screen_height))
        else:
            imgout = ImageOps.pad(imgin, (screen_width, screen_height),
                                  color=fillcolor,
                                  centering=(0.5, 0.5))
        imgout.save(output_png, mode="RGBA", format="PNG")
Ejemplo n.º 19
0
    def display_image(self, filename):
        if not filename:
            return

        pil_image = Image.open(filename)
        canvas_width = self.canvas.winfo_width()
        canvas_height = self.canvas.winfo_height()
        pad_image = ImageOps.pad(pil_image, (canvas_width, canvas_height),
                                 color=self.back_color)
        self.photo_image = ImageTk.PhotoImage(image=pad_image)
        self.width = pil_image.width
        self.height = pil_image.height

        scale_x = pil_image.width / pad_image.width
        scale_y = pil_image.height / pad_image.height
        self.scale = max(scale_x, scale_y)
        self.trans = [0, 0]

        if (pil_image.width / self.scale) != pad_image.width:
            self.trans[0] = (self.scale * canvas_width - pil_image.width) / 2.0
        if (pil_image.height / self.scale) != pad_image.height:
            self.trans[1] = (self.scale * canvas_height -
                             pil_image.height) / 2.0

        self.canvas.create_image(canvas_width / 2,
                                 canvas_height / 2,
                                 image=self.photo_image)
Ejemplo n.º 20
0
 def _receive_messages(self) -> None:
     """Receive messages from the server."""
     while True:
         try:
             with self.recv_lock:
                 msg_type, msg = open_package(self.session.srv_key,
                                              self.private_key, self.socket)
             if len(msg) == 0:
                 break
             if msg_type == 'MSG':
                 sG.cprint(msg.decode())
             elif msg_type == 'SES':
                 self._set_session_vars(msg.decode())
                 continue
             elif msg_type == 'FOL':
                 self._folders_and_files(msg.decode())
                 continue
             elif msg_type == 'IMG':
                 img = Image.open(BytesIO(msg))
                 img = ImageOps.pad(img, self.media_size)
                 with BytesIO() as bio:
                     img.save(bio, format="PNG")
                     del img
                 self.media = bio.getvalue()
                 continue
             elif msg_type == 'ERR':
                 sG.PopupError(msg.decode())
         except OSError:
             self.recv_lock.release()
         finally:
             t.sleep(0.1)
Ejemplo n.º 21
0
 def show(self):
     """Start the slideshow"""
     image = Image.open(self.images[self.index])
     image = ImageOps.pad(image, (980, 780))
     with BytesIO() as bio:
         image.save(bio, format="PNG")
         del image
         self.window['IMAGE'].update(data=bio.getvalue())
Ejemplo n.º 22
0
def add_margins(sample_path: Path, color: str = "#282c34"):
    im: Image.Image = Image.open(sample_path).convert("RGB")
    new_w = round((im.height / 10) * 16)
    im.load()
    new_im = ImageOps.pad(
        im, (new_w, im.height), method=Image.NEAREST, color=color
    )
    new_im.save(sample_path)
Ejemplo n.º 23
0
 def loadImage(self, ind):
   ind = int(ind)
   self._currentInd = ind
   imageList = glob.glob(f"image{ind}.*")
   if (not imageList):
     return
   print (f"Loading: {imageList[0]}")
   self.lock.acquire()
   try:
     if (imageList):
       image = Image.open(imageList[0])
       duration = 0
       self._frames.clear()
       if ('jfif' in image.info):
         #jpg
         duration = 5000
         self._frame_count = 1
         frame_object = Frame(duration=duration)
         frame_object.image = ImageOps.pad(  # pylint: disable=no-member
           image.convert("RGB"),
           (self._width, self._height),
           method=Image.NEAREST,
           color=(0, 0, 0),
           centering=(0.5, 0.5),
         )
         self._frames.append(frame_object)
       else:
         if "duration" in image.info:
           duration = image.info["duration"]
         self._frame_count = image.n_frames
         for frame in range(self._frame_count):
           image.seek(frame)
           # Create blank image for drawing.
           # Make sure to create image with mode 'RGB' for full color.
           frame_object = Frame(duration=duration)
           frame_object.image = ImageOps.pad(  # pylint: disable=no-member
             image.convert("RGB"),
             (self._width, self._height),
             method=Image.NEAREST,
             color=(0, 0, 0),
             centering=(0.5, 0.5),
           )
           self._frames.append(frame_object)
   finally:
     self.lock.release()
Ejemplo n.º 24
0
def display_image(driver,
                  image,
                  stretch=False,
                  no_resize=False,
                  fill_color="white",
                  rotate=None,
                  mirror=None,
                  flip=None):
    """
    Display the given image using the given driver and options.
    :param driver: device driver (subclass of `WaveshareEPD`)
    :param image: image data to display
    :param stretch: whether to stretch the image so that it fills the screen in both dimentions
    :param no_resize: whether the image should not be resized if it does not fit the screen (will raise `RuntimeError`
    if image is too large)
    :param fill_color: colour to fill space when image is resized but one dimension does not fill the screen
    :param rotate: rotate the image by arbitrary degrees
    :param mirror: flip the image horizontally
    :param flip: flip the image vertically
    :return: the image that was rendered
    """
    if stretch and no_resize:
        raise ValueError('Cannot set "no-resize" with "stretch"')

    if mirror:
        image = ImageOps.mirror(image)
    if flip:
        image = ImageOps.flip(image)
    if rotate:
        image = image.rotate(rotate, expand=True, fillcolor=fill_color)

    image_width, image_height = image.size

    if stretch:
        if (image_width, image_height) == (driver.width, driver.height):
            output_image = image
        else:
            output_image = image.resize((driver.width, driver.height))
    else:
        if no_resize:
            if image_width > driver.width or image_height > driver.height:
                raise RuntimeError(
                    'Image ({0}x{1}) needs to be resized to fit the screen ({2}x{3})'
                    .format(image_width, image_height, driver.width,
                            driver.height))
            # Pad only
            output_image = Image.new(image.mode, (driver.width, driver.height),
                                     color=fill_color)
            output_image.paste(image, (0, 0))
        else:
            # Scales and pads
            output_image = ImageOps.pad(image, (driver.width, driver.height),
                                        color=fill_color)

    driver.draw(0, 0, output_image)

    return output_image
Ejemplo n.º 25
0
def test_pad():
    # Same ratio
    im = hopper()
    new_size = (im.width * 2, im.height * 2)
    new_im = ImageOps.pad(im, new_size)
    assert new_im.size == new_size

    for label, color, new_size in [
        ("h", None, (im.width * 4, im.height * 2)),
        ("v", "#f00", (im.width * 2, im.height * 4)),
    ]:
        for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):
            new_im = ImageOps.pad(im, new_size, color=color, centering=centering)
            assert new_im.size == new_size

            assert_image_similar_tofile(
                new_im, "Tests/images/imageops_pad_" + label + "_" + str(i) + ".jpg", 6
            )
Ejemplo n.º 26
0
 def crop(self, box, black_border=False):
     """
     Crop pixels according to offset provided by box
     """
     height, width = self.shape
     cropped = self.image.crop(box)
     if black_border:
         return Image(ImageOps.pad(cropped, (width, height)))
     else:
         return Image(cropped)
Ejemplo n.º 27
0
def fit_screen(self: Image.Image):
    ratio_width = SCREEN_WIDTH / self.size[0]
    ratio_height = SCREEN_HEIGHT / self.size[1]
    ratio = ratio_width if ratio_width < ratio_height else ratio_height

    new_size = tuple([int(x * ratio) for x in self.size])
    new_image = ImageOps.pad(self.resize(new_size, Image.ANTIALIAS),
                             (SCREEN_WIDTH, SCREEN_HEIGHT),
                             color='white')
    return new_image
Ejemplo n.º 28
0
    def test_pad(self):
        # Same ratio
        im = hopper()
        new_size = (im.width * 2, im.height * 2)
        new_im = ImageOps.pad(im, new_size)
        self.assertEqual(new_im.size, new_size)

        for label, color, new_size in [
            ("h", None, (im.width * 4, im.height * 2)),
            ("v", "#f00", (im.width * 2, im.height * 4))
        ]:
            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):
                new_im = ImageOps.pad(im, new_size,
                                      color=color, centering=centering)
                self.assertEqual(new_im.size, new_size)

                target = Image.open(
                    "Tests/images/imageops_pad_"+label+"_"+str(i)+".jpg")
                self.assert_image_similar(new_im, target, 6)
Ejemplo n.º 29
0
    def test_pad(self):
        # Same ratio
        im = hopper()
        new_size = (im.width * 2, im.height * 2)
        new_im = ImageOps.pad(im, new_size)
        self.assertEqual(new_im.size, new_size)

        for label, color, new_size in [
            ("h", None, (im.width * 4, im.height * 2)),
            ("v", "#f00", (im.width * 2, im.height * 4)),
        ]:
            for i, centering in enumerate([(0, 0), (0.5, 0.5), (1, 1)]):
                new_im = ImageOps.pad(im, new_size, color=color, centering=centering)
                self.assertEqual(new_im.size, new_size)

                with Image.open(
                    "Tests/images/imageops_pad_" + label + "_" + str(i) + ".jpg"
                ) as target:
                    self.assert_image_similar(new_im, target, 6)
Ejemplo n.º 30
0
 def scale_and_pad_array(image_array: np.ndarray, output_width: int,
                         output_height: int) -> np.ndarray:
     return np.array(
         ImageOps.pad(
             Image.fromarray(image_array),
             (output_width, output_height),
             method=Image.BICUBIC,
             color=None,
             centering=(0, 0),
         ))
Ejemplo n.º 31
0
def padding(img, expected_size=(280, 520)):
    desired_size_w = expected_size[0]
    desired_size_h = expected_size[1]
    #delta_width = desired_size_w - img.size[0]
    #delta_height = desired_size_h - img.size[1]
    #pad_width = delta_width //2
    #pad_height = delta_height //2
    #padding = (pad_width,pad_height,delta_width-pad_width,delta_height-pad_height)
    #return ImageOps.expand(img, padding)
    return ImageOps.pad(img, expected_size)
Ejemplo n.º 32
0
    def prepare_upload(self, df: pd.DataFrame, experiment_name: str) -> List[VideoUpload]:
        """ Create experiment data locally for video upload, upload to s3, return details
        input: df contains imbag_id and image_id columns -> look for images of form {image_id}.jpg
        output: list of video upload metadata instances (for passing to dataset.populate_dataset_videos)
        """
        uploads = []

        for imbag_id, df_group in df.groupby('imbag_id'):
            image_ids = df_group['image_id'].tolist()
            input_images = [f'{self.local_src}/{image_id}.jpg' for image_id in image_ids]
            output_images = [f'{self.local_root}/{experiment_name}/{imbag_id}_{image_id}.jpg' for image_id in image_ids]
            output_avi_path = f'{self.local_root}/{experiment_name}/{imbag_id}.avi'
            output_thumb_paths = [f'{self.local_root}/{experiment_name}/_thumbs/{imbag_id}_{image_id}.jpg'
                                  for image_id in image_ids]

            s3_output_images = [f'{self.s3_root}/{experiment_name}/{imbag_id}_{image_id}.jpg' for image_id in image_ids]
            s3_output_avi_path = f'{self.s3_root}/{experiment_name}/{imbag_id}.avi'
            s3_output_thumb_paths = [f'_thumbs/{self.s3_root}/{experiment_name}/{imbag_id}_{image_id}.jpg'
                                     for image_id in image_ids]

            # save avi file
            ims = [imageio.imread(input_image) for input_image in input_images]
            shapes = [im.shape for im in ims]
            max_dim = None
            if not all(x == shapes[0] for x in shapes):
                max_dim = max(max(x[0] for x in shapes), max(x[1] for x in shapes))
                ims = [np.array(ImageOps.pad(Image.fromarray(im), [max_dim, max_dim])) for im in ims]
            imageio.mimwrite(output_avi_path, ims, 'FFMPEG', fps=1, macro_block_size=1, codec='mjpeg', quality=10)

            # save images
            w, h, _ = shapes[0] if max_dim is None else [max_dim, max_dim, 0]
            for im, output_path, output_thumb_path in zip(ims, output_images, output_thumb_paths):
                imageio.imwrite(output_path, im, quality=100)
                # create thumb also
                pil_im = Image.fromarray(im)
                sf = min(1.0, 356 / max(w, h))
                pil_im.thumbnail([w * sf, h * sf])
                pil_im.save(output_thumb_path, quality=50)

            # prepare upload object
            uploads.append(VideoUpload(
                filename=imbag_id,
                s3_vid_path=s3_output_avi_path,
                s3_image_paths=[S3Path(path=path, thumb_path=thumb_path)
                                for path, thumb_path in zip(s3_output_images, s3_output_thumb_paths)],
                width=w,
                height=h
            ))

        # upload to s3
        print('Run the following to upload processed data to S3:')
        print(f'aws s3 cp {self.local_root}/{experiment_name} s3://{self.s3_bucket}/{self.s3_root}/{experiment_name}/ --recursive --exclude "*thumbs*"')
        print(f'aws s3 cp {self.local_root}/{experiment_name}/_thumbs s3://{self.s3_bucket}/{self.s3_root}/{experiment_name}/ --recursive')

        return uploads