Home > Net >  How to place object randomly on Different angle and different position python
How to place object randomly on Different angle and different position python

Time:10-01

I want to make a function which generate a dataset, The object will be place on the black image at different position with different angle, different size and place randomly maximum up to 20 time in image. and Save the x,y and angle position in the text file.

Input image

The following image is for five objects at different position and angle.

Output image for five objects

import numpy as np
import cv2
patch=cv2.imread('imagersult.png')
img = np.zeros((2048, 2048, 1), dtype = "uint8")

CodePudding user response:

Here is how you can use the enter image description here

enter image description here

enter image description here

For grayscale and variation in size of the patches:

import numpy as np
import cv2
from random import randrange, uniform
from scipy import ndimage

def patch_img(img, patch, amt=5):
    h, w = img.shape
    min_scale = 0.5
    max_scale = 2
    for _ in range(amt):
        patch_h, patch_w = patch.shape
        scale = uniform(min_scale, max_scale)
        p = ndimage.rotate(cv2.resize(patch, (int(patch_w * scale), int(patch_h * scale))), randrange(360))
        p_h, p_w = p.shape
        x = randrange(w - p_w)
        y = randrange(h - p_h)
        seg = img[y: y   p_h, x: x   p_w]
        seg[:] = cv2.bitwise_xor(seg, p)

patch = cv2.imread('imagersult.png', 0)

img = np.zeros((2048, 2048), dtype="uint8")
patch_img(img, patch)

cv2.imshow("Image", img)
cv2.imwrite("result.png", img)
cv2.waitKey(0)

Sample output:

enter image description here

  • Related