使用PIL进行图片处理

1. 随机旋转和随机缩放

from PIL import Image
import numpy as np
import os

def scale_rotate_img(image, rotate_min=20, rotate_max=70, scale_min=0.4, scale_max=0.8):
    random_rotate = np.random.randint(rotate_min, rotate_max + 1)
    print(random_rotate)
    image = image.rotate(random_rotate, Image.NEAREST, expand = 1)
    
    random_resize = np.random.randint(scale_min * 10, (scale_max + 0.1) * 10)
    random_resize = random_resize / 10
    origin_size = image.size[0]
    scaled_size = int(origin_size * random_resize)
    
    image = image.resize((scaled_size, scaled_size), Image.ANTIALIAS)
    return image

2. 图片嵌入

  这里指的是把一张图片嵌入到另外一张图片中。

def merge_two_imgs(foreground_imgs, background_imgs, result_img):
    background = Image.open(background_imgs)
    foreground = Image.open(foreground_imgs)
    
    foreground = scale_rotate_img(foreground)
    
    paste_x = np.random.randint(0, background.size[0] - foreground.size[0])
    paste_y = np.random.randint(0, background.size[1] - foreground.size[1])
    
    background.paste(foreground, (paste_x, paste_y), foreground)
    background.save(result_img,"PNG")
发布了178 篇原创文章 · 获赞 389 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/herosunly/article/details/105137446