1

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)
xnet
  • 511
  • 2
  • 7
  • 16
  • 3
    Draw the polygon into a black image to create a mask, and then use the mask to blend the two images together. – Dan Mašek Mar 13 '19 at 20:54
  • What function do you use to "paste" the cropped polygon on the target image? – xnet Mar 14 '19 at 18:02
  • There are various different ways... using indexing like [here](https://stackoverflow.com/a/22256245/3962537), `numpy.copyto`, `numpy.where`, or (if you draw with antialising) you can alpha blend like i show [here](https://stackoverflow.com/a/37198079/3962537). – Dan Mašek Mar 14 '19 at 18:23

0 Answers0