本篇博客实现把卡片随机旋转一下
import cv2
from imutils import paths
import imutils
import random
import os
def merge_image(back_path, card_path, new_path):
back_paths = sorted(list(paths.list_images(back_path)))
card_paths = sorted(list(paths.list_images(card_path)))
for i in range(len(card_paths)) :
a = int(random.random() * len(card_paths))
image_card = cv2.imread(card_paths[a])
if image_card is None:
a += 1
print(file_name)
angle = int(random.random() * 10 - 5)
image_card = imutils.rotate_bound(image_card, angle=angle)
image_height, image_width = image_card.shape[:2]
image_back = cv2.imread(back_paths[int(random.random() * len(back_paths))])
image_back = cv2.resize(image_back, (int(image_width *(1 + 1 * random.random())), int( image_height * (1.5 + 1 * random.random()) )))
image_back_height, image_back_width = image_back.shape[:2]
x = random.uniform(0.1, 0.9) * (image_back_width - image_width)
y = random.uniform(0.1, 0.9) * (image_back_height - image_height)
left = int(x)
right = int(x) + image_width
top = int(y)
bottom = int(y) + image_height
mask = image_card > 0
image_card_temp = image_back[top:bottom, left:right]
image_card_temp[mask] = image_card[mask]
image_back[top:bottom, left:right] = image_card_temp
file_name = "{}.jpg".format(i)
file_name = os.path.sep.join([new_path, file_name])
cv2.imwrite(file_name, image_back)
if __name__ == "__main__":
merge_image(r'G:\back', r'G:\card',
r'G:\new')
上面代码实现的功能是: 把一张小卡卡,以随机角度/随机位置融合到背景图上.