Python PIL.Image.new() Examples

The following are 30 code examples of PIL.Image.new(). 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.Image , or try the search function .
Example #1
Source File: polapizero_03.py    From polapi-zero with MIT License 7 votes vote down vote up
def displayImageFileOnLCD(filename):
    print 'displays ', filename
    title = 'Review Mode'
    # resize/dither to screen resolution and send to LCD
    image = Image.open(filename)
    im_width, im_height = image.size
    if im_width < im_height:
        image = image.rotate(90)
    image.thumbnail(S_SIZE, Image.ANTIALIAS)
    image_sized = Image.new('RGB', S_SIZE, (0, 0, 0))
    image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2))
    # draw filename
    draw = ImageDraw.Draw(image_sized)
    font = ImageFont.truetype('arial.ttf', 18)
    draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0))
    draw.text((2, 2), title, fill='black', font=font)
    draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0))
    draw.text((290, 218), filename, fill='black', font=font)
    # display on LCD
    image_sized = ImageOps.invert(image_sized)
    image_sized = image_sized.convert('1') # convert image to black and white
    lcd.write(image_sized.tobytes()) 
Example #2
Source File: autocaptcha.py    From sjtu-automata with GNU General Public License v3.0 6 votes vote down vote up
def autocaptcha(path):
    """Auto identify captcha in path.

    Use pytesseract to identify captcha.

    Args:
        path: string, image path.

    Returns:
        string, OCR identified code.
    """
    im = Image.open(path)

    im = im.convert('L')
    im = ImageEnhance.Contrast(im)
    im = im.enhance(3)
    img2 = Image.new('RGB', (150, 60), (255, 255, 255))
    img2.paste(im.copy(), (25, 10))

    # TODO: add auto environment detect
    return pytesseract.image_to_string(img2) 
Example #3
Source File: utils.py    From pytorch-segmentation-toolbox with MIT License 6 votes vote down vote up
def decode_labels(mask, num_images=1, num_classes=21):
    """Decode batch of segmentation masks.
    
    Args:
      mask: result of inference after taking argmax.
      num_images: number of images to decode from the batch.
      num_classes: number of classes to predict (including background).
    
    Returns:
      A batch with num_images RGB images of the same size as the input. 
    """
    mask = mask.data.cpu().numpy()
    n, h, w = mask.shape
    assert(n >= num_images), 'Batch size %d should be greater or equal than number of images to save %d.' % (n, num_images)
    outputs = np.zeros((num_images, h, w, 3), dtype=np.uint8)
    for i in range(num_images):
      img = Image.new('RGB', (len(mask[i, 0]), len(mask[i])))
      pixels = img.load()
      for j_, j in enumerate(mask[i, :, :]):
          for k_, k in enumerate(j):
              if k < num_classes:
                  pixels[k_,j_] = label_colours[k]
      outputs[i] = np.array(img)
    return outputs 
Example #4
Source File: OP_1_Connection.py    From OP_Manager with MIT License 6 votes vote down vote up
def check_OP_1_Connection():
    connected = Image.new('1', (128, 64))
    draw = ImageDraw.Draw(connected)
    draw.text((0, 25), "Connecting.....", font=getFont(), fill='white')
    displayImage(connected)

    # if is_connected():
    if do_mount("OP1"):
        connected = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(connected)
        draw.text((0, 25), "Connected", font=getFont(), fill='white')
        displayImage(connected)
        return True
    else:
        connected = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(connected)
        draw.text((0, 25), "No Connection!", font=getFont(), fill='white')
        displayImage(connected)
        config["USB_Mount_Path"] = ""
        config["OP_1_Mounted_Dir"] = ""
        time.sleep(1)
        return False 
Example #5
Source File: OP_1_Connection.py    From OP_Manager with MIT License 6 votes vote down vote up
def unmount_OP_Z():
    if getMountPath("OPZ") != "":
        unmountDisplay = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(unmountDisplay)
        draw.text((30, 25), "Ejecting!", font=getFont(), fill='white')
        displayImage(unmountDisplay)
        unmountdevice(config["OP_Z_Mounted_Dir"])
        config["USB_Mount_Path"] = ""
        unmountDisplay = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(unmountDisplay)
        draw.text((30, 25), "Ejected!", font=getFont(), fill='white')
        displayImage(unmountDisplay)
        time.sleep(1)
        return True
    else:
        unmountDisplay = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(unmountDisplay)
        draw.text((15, 25), "No Device to Eject", font=getFont(), fill='white')
        displayImage(unmountDisplay)
        time.sleep(1)
        return False 
Example #6
Source File: gradient.py    From wallgen with MIT License 6 votes vote down vote up
def nGradient(side, *colors):
	img = Image.new("RGB", (side,side), "#FFFFFF")
	draw = ImageDraw.Draw(img)

	nc = len(colors)
	div = side//(nc-1)
	[r,g,b] = colors[0]
	p=0
	for i in range(1,nc):
		dc = [(y-x)/div for x,y in zip(colors[i-1], colors[i])]
		for x in range(p, p+div):
			draw.line([x,0,x,side], fill=tuple(map(int, [r,g,b])))
			r+=dc[0]
			g+=dc[1]
			b+=dc[2]
		p+=div
	
	return img 
Example #7
Source File: shapes.py    From wallgen with MIT License 6 votes vote down vote up
def drawSlants(side):
	randcolor = lambda : (randint(0,255),randint(0,255),randint(0,255))

	img = Image.new("RGB", (side,side), "#FFFFFF")
	draw = ImageDraw.Draw(img)
	y = 0
	min_w = int(side * 0.01)
	max_w = int(side * 0.1)
	adj = max_w * 2
	while y <= side+adj:
		w = randint(min_w, max_w)
		c = randcolor()
		draw.line([-adj , y,  y, -adj], width=w, fill=c)
		draw.line([y, side+adj,  side+adj, y], width=w, fill=c)
		y+=w

	return img


#################
# TRIANGULATION #
################# 
Example #8
Source File: show_my_ip.py    From unicorn-hat-hd with MIT License 6 votes vote down vote up
def create_image_from_text(in_text):
    colours = (255, 255, 250)
    font_file = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'
    font_size = 12
    font = ImageFont.truetype(font_file, font_size)
    w, h = font.getsize(in_text)

    text_x, text_y = width, 0
    text_width, text_height = width, 0

    text_width += w + width                # add some padding so the ip scrolls off the unicorn hat
    text_height = max(text_height, h, 16)  # no more than the size of the unicorn hat

    image = Image.new('RGB', (text_width, text_height), (0, 0, 0))
    draw = ImageDraw.Draw(image)
    draw.text((text_x, text_y), in_text, colours, font=font)
    return (image, text_width)


# DISPLAY 
Example #9
Source File: work_vcode.py    From TaiwanTrainVerificationCode2text with Apache License 2.0 6 votes vote down vote up
def draw(self, image, overlay):
        if((overlay or not self.luoverlay) and not self.ludrawn):
            self.ludrawn = True
            stp = self.location
            transparent = int(255 * 0.45 if self.lucolor == 0 else 255 * 0.8)
            color = (self.lucolor, self.lucolor, self.lucolor, transparent)
            uline = Image.new("RGBA", (self.size[0], 1), color)
            lline = Image.new("RGBA", (1, self.size[1]), color)
            image.paste(uline, stp, uline)
            image.paste(lline, stp, lline)
        if((overlay or not self.rdoverlay) and not self.rddrawn):
            self.rddrawn = True
            dstp = (self.location[0], self.location[1] + self.size[1])
            rstp = (self.location[0] + self.size[0], self.location[1])
            transparent = int(255 * 0.45 if self.rdcolor == 0 else 255 * 0.8)
            color = (self.rdcolor, self.rdcolor, self.rdcolor, transparent)
            dline = Image.new("RGBA", (self.size[0], 1), color)
            rline = Image.new("RGBA", (1, self.size[1]), color)
            image.paste(dline, dstp, dline)
            image.paste(rline, rstp, rline) 
Example #10
Source File: work_vcode.py    From TaiwanTrainVerificationCode2text with Apache License 2.0 6 votes vote down vote up
def draw(self, image):
        
        fontpath = FONTPATH[ random.sample(range(2),1)[0] ] 
        color = (self.color[0], self.color[1], self.color[2], 255)
        font = ImageFont.truetype( fontpath , randint(25, 27) * 10)
        text = Image.new("RGBA", (250, 300), (0, 0, 0, 0))
        textdraw = ImageDraw.Draw(text)
        
        textdraw.text((0, 0), str(self.number), font=font, fill=color)
        #textdraw.text((0, 0), 'j', font=font, fill=color)

        text = text.rotate(self.angle, expand=True)
        text = text.resize((int(text.size[0] / 10), int(text.size[1] / 10)))
        base = int(self.priority * (200 / 6))
        rand_min = (self.offset - base - 2) if (self.offset - base - 2) >= -15 else -15
        rand_min = 0 if self.priority == 0 else rand_min
        rand_max = (33 - text.size[0]) if self.priority == 5 else (33 - text.size[0] + 10)
        try:
            displace = randint(rand_min, rand_max)
        except:
            displace = rand_max
        location = (base + displace, randint(3, 23))
        self.next_offset = location[0] + text.size[0]
        image.paste(text, location, text)
        # plt.imshow(image) 
Example #11
Source File: pgn2gif.py    From pgn2gif with MIT License 6 votes vote down vote up
def generate_board():
    global initial_board
    initial_board = Image.new('RGB', (BOARD_EDGE, BOARD_EDGE))

    for i in range(0, BOARD_EDGE, SQUARE_EDGE):
        for j in range(0, BOARD_EDGE, SQUARE_EDGE):
            clear(initial_board, (i, j))

    row = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']
    order = ('w', 'b') if reverse else ('b', 'w')

    for i in range(8):
        col = SQUARE_EDGE * i
        exec('initial_board.paste({0}, (col, 0), {0})'
            .format(order[0] + row[i]))
        exec('initial_board.paste({0}, (col, BOARD_EDGE - SQUARE_EDGE), {0})'
            .format(order[1] + row[i]))

        exec('initial_board.paste({0}p, (col, SQUARE_EDGE), {0}p)'
            .format(order[0]))
        exec(
            'initial_board.paste({0}p, (col, BOARD_EDGE - (SQUARE_EDGE * 2)), {0}p)'
            .format(order[1])) 
Example #12
Source File: util.py    From bnn with MIT License 6 votes vote down vote up
def debug_img(img, bitmap, logistic_output):
  # create a debug image with three columns; 1) original RGB. 2) black/white
  # bitmap of labels 3) black/white bitmap of predictions (with centroids coloured
  # red.
  h, w, _channels = bitmap.shape
  canvas = Image.new('RGB', (w*3, h), (50, 50, 50))
  # original input image on left
  img = zero_centered_array_to_pil_image(img)
  img = img.resize((w, h))
  canvas.paste(img, (0, 0))
  # label bitmap in center
  canvas.paste(bitmap_to_pil_image(bitmap), (w, 0))
  # logistic output on right
  canvas.paste(bitmap_to_pil_image(logistic_output), (w*2, 0))
  # draw red dots on right hand side image corresponding to
  # final thresholded prediction
  draw = ImageDraw.Draw(canvas)
  for y, x in centroids_of_connected_components(logistic_output):
    draw.rectangle((w*2+x,y,w*2+x,y), fill='red')
  # finally draw blue lines between the three to delimit boundaries
  draw.line([w,0,w,h], fill='blue')
  draw.line([2*w,0,2*w,h], fill='blue')
  draw.line([3*w,0,3*w,h], fill='blue')
  # done
  return canvas 
Example #13
Source File: util.py    From bnn with MIT License 6 votes vote down vote up
def side_by_side(rgb, bitmap):
  h, w, _ = rgb.shape
  canvas = Image.new('RGB', (w*2, h), (50, 50, 50))
  # paste RGB on left hand side
  lhs = zero_centered_array_to_pil_image(rgb)
  canvas.paste(lhs, (0, 0))
  # paste bitmap version of labels on right hand side
  # black with white dots at labels
  rhs = bitmap_to_pil_image(bitmap)
  rhs = rhs.resize((w, h))
  canvas.paste(rhs, (w, 0))
  # draw on a blue border (and blue middle divider) to make it
  # easier to see relative positions.
  draw = ImageDraw.Draw(canvas)
  draw.polygon([0,0,w*2-1,0,w*2-1,h-1,0,h-1], outline='blue')
  draw.line([w,0,w,h], fill='blue')
  canvas = canvas.resize((w, h//2))
  return canvas 
Example #14
Source File: dump_bee_crops.py    From bnn with MIT License 6 votes vote down vote up
def valid(labels, cx, cy):
  # is idxth item in labels "valid"? where "valid" => bounding
  # box within image and no other bee in bounding box.
  x1, y1 = cx-HW, cy-HW
  if x1 < 0 or y1 < 0:
    # either left or top margin out of bounds => invalid
    return False
  x2, y2 = cx+HW, cy+HW
  if x2 > opts.width or y2 > opts.height:
    # either right or bottom margin out of bounds => invalid
    return False
  for ox, oy in labels:
    if ox == cx and oy == cy:
      # this 'other' bee is the one being checked => ignore
      continue
    if x1 < ox and ox < x2 and y1 < oy and oy < y2:
      # other bee inside bounding box => invalid
      return False
  return True

#canvas = Image.new('RGB', (HW*20, HW*20), (0,0,0)) 
Example #15
Source File: reverse_optimise.py    From bnn with MIT License 6 votes vote down vote up
def dump_images(prefix):
  # run from imgs -> bitmap and stitch them together...
  img_collage = Image.new('RGB', (17*8, 17*8), (0, 0, 0))
  bitmap_collage = Image.new('RGB', (9*8, 9*8), (255, 255, 255))
  centroids_collage = Image.new('RGB', (9*8, 9*8), (255, 255, 255))
  ims, bs = sess.run([imgs, model.output])
  for x in range(8):
    for y in range(8):
      i = (x * 8) + y
      img_collage.paste(u.zero_centered_array_to_pil_image(ims[i]), (17*x, 17*y))
      output_bitmap = u.bitmap_to_pil_image(bs[i])
      bitmap_collage.paste(output_bitmap, (9*x, 9*y))
      centroids = u.centroids_of_connected_components(bs[i])
      centroid_bitmap = u.bitmap_from_centroids(centroids, h=8, w=8)
      centroid_bitmap = u.bitmap_to_single_channel_pil_image(centroid_bitmap)
      centroids_collage.paste(centroid_bitmap, (9*x, 9*y))
  img_collage.save("images/ra/%s_imgs.png" % prefix)
  bitmap_collage.save("images/ra/%s_bitmaps.png" % prefix)
  centroids_collage.save("images/ra/%s_centroids.png" % prefix) 
Example #16
Source File: mask_face_region_with_avail_kpts.py    From DepthNets with MIT License 6 votes vote down vote up
def tile_images(img, img_mask, img_depthNet, row_size, col_size):
    rows = 1
    cols = 3

    gap_sz = 5
    gap_cols = (cols - 1) * gap_sz
    gap_rows = (rows - 1) * gap_sz
    index = 0

    new_im = Image.new('RGB', (cols*col_size + gap_cols,
                               rows*row_size + gap_rows), "white")
    for i in xrange(0, rows * row_size + gap_rows, row_size + gap_sz):
        for jj in xrange(0, cols * col_size + gap_cols, col_size + gap_sz):
            if jj == 0:
                new_im.paste(img, (jj, i))
            elif jj == col_size + gap_sz:
                new_im.paste(img_mask, (jj, i))
            else:
                new_im.paste(img_depthNet, (jj, i))
    return new_im 
Example #17
Source File: make_VGG_dataset_sina.py    From DepthNets with MIT License 6 votes vote down vote up
def tile_images(img_orig, img_mask_bck, img_mask_face, img_frontalized_PIL,
                row_size, col_size):
    rows = 1 
    cols = 4

    gap_sz = 5
    gap_cols = (cols - 1) * gap_sz
    gap_rows = (rows - 1) * gap_sz
    index = 0

    new_im = Image.new('RGB', (cols*col_size + gap_cols,
                               rows*row_size + gap_rows), "white")
    for i in range(0, rows * row_size + gap_rows, row_size + gap_sz):
        for jj in range(0, cols * col_size + gap_cols, col_size + gap_sz):
            if jj == 0:
                new_im.paste(img_orig, (jj, i))
            elif jj == col_size + gap_sz:
                new_im.paste(img_mask_bck, (jj, i))
            elif jj == 2 * (col_size + gap_sz):
                new_im.paste(img_mask_face, (jj, i))
            else:
                new_im.paste(img_frontalized_PIL, (jj, i))
    return new_im 
Example #18
Source File: transforms.py    From Parsing-R-CNN with MIT License 6 votes vote down vote up
def image_crop_with_padding(self, img, crop_region, crop_shape):
        set_left, set_up, right, bottom = crop_region
        crop_left, corp_up = max(set_left, 0), max(set_up, 0)
        crop_region = (crop_left, corp_up, right, bottom)

        img = img.crop(crop_region)
        if img.size != crop_shape:
            pad_img = Image.new('RGB', crop_shape, self.pad_pixel)
            paste_region = (max(0-set_left, 0),
                            max(0-set_up, 0),
                            max(0-set_left, 0)+img.size[0],
                            max(0-set_up, 0)+img.size[1])
            pad_img.paste(img, paste_region)
            return pad_img

        return img 
Example #19
Source File: OP_1_Connection.py    From OP_Manager with MIT License 5 votes vote down vote up
def unmount_OP_1():
    if getMountPath("OP1") != "":
        unmountDisplay = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(unmountDisplay)
        draw.text((30, 25), "Ejecting!", font=getFont(), fill='white')
        displayImage(unmountDisplay)
        unmountdevice(config["OP_1_Mounted_Dir"])
        config["OP_1_Mounted_Dir"] = ""
        config["USB_Mount_Path"] = ""
        unmountDisplay = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(unmountDisplay)
        draw.text((30, 25), "Ejected", font=getFont(), fill='white')
        displayImage(unmountDisplay)
        time.sleep(1)
        return True
    elif os.path.isdir(config["OP_Z_Mounted_Dir"]):
        unmountdevice(config["OP_Z_Mounted_Dir"])
        unmountDisplay = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(unmountDisplay)
        draw.text((15, 25), "Ejected", font=getFont(), fill='white')
        displayImage(unmountDisplay)
        time.sleep(1)
        return True

    else:
        unmountDisplay = Image.new('1', (128, 64))
        draw = ImageDraw.Draw(unmountDisplay)
        draw.text((15, 25), "No Device to Eject", font=getFont(), fill='white')
        displayImage(unmountDisplay)
        time.sleep(1)
        return False


# ============= OP1 Helper tools ================= 
Example #20
Source File: image_utils.py    From ObjectPoseEstimationSummary with MIT License 5 votes vote down vote up
def resize_padding(im, desired_size):
    # compute the new size
    old_size = im.size
    ratio = float(desired_size) / max(old_size)
    new_size = tuple([int(x * ratio) for x in old_size])

    im = im.resize(new_size, Image.BILINEAR)

    # create a new image and paste the resized on it
    new_im = Image.new("RGBA", (desired_size, desired_size))
    new_im.paste(im, ((desired_size - new_size[0]) // 2, (desired_size - new_size[1]) // 2))
    return new_im 
Example #21
Source File: test.py    From Semantic-Segmentation with MIT License 5 votes vote down vote up
def letterbox_image(image, size, type):
    '''resize image with unchanged aspect ratio using padding'''
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)
    
    image = image.resize((nw,nh), Image.BICUBIC)
    if(type=="jpg"):
        new_image = Image.new('RGB', size, (0,0,0))
    elif(type=="png"):
        new_image = Image.new('RGB', size, (0,0,0))
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    return new_image,nw,nh 
Example #22
Source File: image_fetcher.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def save_composite_image(in_filepaths: List[str], out_filepath: str) -> None:
    images = list(map(Image.open, in_filepaths))
    for image in images:
        aspect_ratio = image.width / image.height
        image.thumbnail([aspect_ratio * 445, 445])
    widths, heights = zip(*(i.size for i in images))
    total_width = sum(widths)
    max_height = max(heights)
    new_image = Image.new('RGB', (total_width, max_height))
    x_offset = 0
    for image in images:
        new_image.paste(image, (x_offset, 0))
        x_offset += image.size[0]
    new_image.save(out_filepath) 
Example #23
Source File: image_utils.py    From ObjectPoseEstimationSummary with MIT License 5 votes vote down vote up
def resize_padding_v2(im, desired_size_in, desired_size_out):
    # compute the new size
    old_size = im.size
    ratio = float(desired_size_in)/max(old_size)
    new_size = tuple([int(x*ratio) for x in old_size])

    im = im.resize(new_size, Image.ANTIALIAS)

    # create a new image and paste the resized on it
    new_im = Image.new("RGBA", (desired_size_out, desired_size_out))
    new_im.paste(im, ((desired_size_out - new_size[0]) // 2, (desired_size_out - new_size[1]) // 2))
    return new_im


# Crop and resize the rendering images 
Example #24
Source File: train.py    From Semantic-Segmentation with MIT License 5 votes vote down vote up
def letterbox_image(image, size, type):
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)
    
    image = image.resize((nw,nh), Image.NEAREST)
    if(type=="jpg"):
        new_image = Image.new('RGB', size, (0,0,0))
    elif(type=="png"):
        new_image = Image.new('RGB', size, (0,0,0))
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    return new_image,nw,nh 
Example #25
Source File: predict.py    From Semantic-Segmentation with MIT License 5 votes vote down vote up
def letterbox_image(image, size):
    '''resize image with unchanged aspect ratio using padding'''
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)

    image = image.resize((nw,nh), Image.BICUBIC)
    new_image = Image.new('RGB', size, (0,0,0))
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    return new_image,nw,nh 
Example #26
Source File: image_fetcher.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def generate_banner(names: List[str], background: str, v_crop: int = 33) -> str:
    cards = [oracle.load_card(name) for name in names]
    out_filepath = determine_filepath(cards, f'banner-{background}{v_crop}-')

    if fetch_tools.acceptable_file(out_filepath):
        return out_filepath

    canvas = Image.new('RGB', (1920, 210))
    c = oracle.load_card(background)
    file_path = await download_scryfall_art_crop(c)
    if file_path:
        with Image.open(file_path) as img:
            h = v_crop / 100 * 1315
            canvas.paste(img.resize((1920, 1315), Image.BICUBIC).crop((0, h, 1920, h + 210)))

    n = math.ceil(len(cards) / 2)
    x = 800
    for c in cards[:n]:
        ip = await download_scryfall_png(c)
        with Image.open(ip) as img:
            img = img.resize((160, 213), Image.LANCZOS)
            canvas.paste(img, (x, 30))
            x = x + img.width + 10
    x = 900
    for c in cards[n:]:
        ip = await download_scryfall_png(c)
        with Image.open(ip) as img:
            img = img.resize((160, 213), Image.LANCZOS)
            canvas.paste(img, (x, 60))
            x = x + img.width + 10

    canvas.save(out_filepath)
    return out_filepath 
Example #27
Source File: clear_screen.py    From rpi_epd2in7 with MIT License 5 votes vote down vote up
def main():
    print("initializing...")
    epd = EPD()
    epd.init()
    print("initialized.")

    image = Image.new('1', (epd.width, epd.height), 255)
    epd.display_frame(image)
    epd.sleep()
    print("Done.") 
Example #28
Source File: utils.py    From keras-yolo3 with MIT License 5 votes vote down vote up
def letterbox_image(image, size):
    '''resize image with unchanged aspect ratio using padding'''
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)

    image = image.resize((nw,nh), Image.BICUBIC)
    new_image = Image.new('RGB', size, (128,128,128))
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    return new_image 
Example #29
Source File: gradient.py    From wallgen with MIT License 5 votes vote down vote up
def NbyNGradient(side):
	base_color = "#00ffff"
	img = Image.new("RGB", (side,side), base_color)
	draw = ImageDraw.Draw(img)

	n_boxes = 5
	boxes_size = side//n_boxes

	xmin, xmax = 0, boxes_size
	ymin, ymax = 0, boxes_size


	for i in range(n_boxes):
		for j in range(n_boxes):
			r, g, b = [randint(0, 255),randint(0, 255), randint(0, 255)]

			dr = (randint(0, 255) - r)/boxes_size
			dg = (randint(0, 255) - g)/boxes_size
			db = (randint(0, 255) - b)/boxes_size
			
			for k in range(xmin, xmax):
				draw.line([k, ymin, k, ymax], fill=(int(r), int(g), int(b)))
				r += dr
				g += dg
				b += db

			xmin += boxes_size
			xmax += boxes_size

		xmin = 0
		xmax = boxes_size
		ymin += boxes_size
		ymax += boxes_size

	img = img.filter(ImageFilter.GaussianBlur(radius=boxes_size//n_boxes))
	return img 
Example #30
Source File: gradient.py    From wallgen with MIT License 5 votes vote down vote up
def random_gradient(side):
	img = Image.new("RGB", (side,side), "#FFFFFF")
	draw = ImageDraw.Draw(img)

	r,g,b = randint(0,255), randint(0,255), randint(0,255)
	dr = (randint(0,255) - r)/side
	dg = (randint(0,255) - g)/side
	db = (randint(0,255) - b)/side
	for i in range(side):
		r,g,b = r+dr, g+dg, b+db
		draw.line((i,0,i,side), fill=(int(r),int(g),int(b)))

	return img