I'm trying to crop a random polygon from one image and pasting it on another. So far I know how to do this for a rectangular box.
Is there a way to crop an n-shaped polygon and paste it onto another image? Thanks!
from PIL import Image
import random
x_rand = random.randrange(0,1080)
y_rand = random.randrange(0,1920)
w_rand = random.randrange(0,min(1080, (1080-x_rand)))
h_rand = random.randrange(0,min(1920, (1920-y_rand)))
# tmp1 - source image path
# tmp2 - target image path
image1 = Image.open(tmp1)
x, y, w, h = (x_rand, y_rand, w_rand, h_rand)
print(x, y, w, h)
box = (x, y, x + w, y + h)
region = image1.crop(box)
image2 = Image.open(tmp2)
image2.paste(region, box)
Ok, I've figured how to cut a polygon image, how do I paste it?
import cv2
import numpy as np
image = cv2.imread(source)
image2 = cv2.imread(target)
# Create white pixel mask
mask = np.ones(image.shape, dtype=np.uint8)
mask.fill(255)
# Specify polyon and crop
roi_corners = np.array([[(0, 300), (200, 300), (300, 400), (0, 400)]], dtype=np.int32)
cv2.fillPoly(mask, roi_corners, 0)
# Crop original image
masked_image = cv2.bitwise_or(image, mask)