Home > Net >  pasting images on white background of size 39*39 randomly anywhere on white background
pasting images on white background of size 39*39 randomly anywhere on white background

Time:07-22

I would like to generate a white image and then paste small 24*24 crops on (images) that white images but it should paste randomly anywhere on that white background. How should I do it?

import os

im1 = Image.open('data/src/white_image.jpg')
for path in dataset_paths:
    im2 = Image.open(path)
    back_im = im1.copy()
    back_im.paste(im2)
    back_im.save(f'data/dst/{os.path.basename(path)}')

also, it should paste randomly anywhere. please help!

CodePudding user response:

Try the following code

import random
from PIL import Image
import os
import glob

dataset_paths = [filename for filename in glob.glob('/home/user/Downloads/Dataset/training/cat/*.png')]

for i, path in enumerate(dataset_paths):
    bg_im = Image.new(mode="RGB", size=(1024, 1024), color="white")
    img = Image.open(path).resize((24, 24))
    
    bg_width, bg_height = bg_im.size
    img_width, img_height = img.size
    max_x = bg_width - (img_width * 2)
    max_y = bg_height - (img_height * 2)

    if max_x < 0 or max_y < 0:
        print("image cannot be completely pasted on background image")
        continue 

    random_x = random.randint(0, max_x)
    random_y = random.randint(0, max_y)

    bg_im.paste(img, box=(random_x, random_y))
    bg_im.save(f'data/dst/{os.path.basename(path}')

PS. I recommend you to use Image.new for creating a background image instead of Image.open. You can replace size of the background image to whatever you need.

CodePudding user response:

As you are using opencv you can just paste the image into the right position.

large_img[y_offset:y_end,x_offset:x_end] = small_img

More in depth explanations can be found here

  • Related