如何从图像A中随机裁剪多边形并将其粘贴到python中的图像B上?

时间:2019-03-13 20:11:07

标签: python opencv computer-vision python-imaging-library

我正在尝试从一个图像中裁剪一个随机多边形,然后将其粘贴到另一个图像上。到目前为止,我知道如何对矩形框执行此操作。

是否可以裁剪n形多边形并将其粘贴到另一个图像上?谢谢!

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)

好吧,我已经知道如何剪切多边形图像,如何粘贴它?

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)

0 个答案:

没有答案