使用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")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章