Skip to content
Advertisement

How do I generate a small image randomly in different parts of the big image?

Let’s assume there are two images. One is called small image and another one is called big image. I want to randomly generate the small image inside the different parts of the big image one at a time everytime I run.

So, currently I have this image. Let’s call it big image

1

I also have smaller image:

2

def mask_generation(blob_index,image_index): 
    experimental_image = markup_images[image_index]
    h, w = cropped_images[blob_index].shape[:2]
    x = np.random.randint(experimental_image.shape[0] - w)
    y = np.random.randint(experimental_image.shape[1] - h)
    experimental_image[y:y+h, x:x+w] = cropped_images[blob_index]
    return experimental_image

I have created above function to generate the small image in big image everytime I call this function. Note: blob index is the index that I use to call specific ‘small image’ since I have a collection of those small images and image_index is the index to call specific ‘big images’. Big images are stored in the list called experimental_image and small images are stored in list called markup images

However, when I run this, I do get the small image randomly generated but the previously randomly generated image never gets deleted and I am not too sure how to proceed with it,

Example: When I run it once

3

When I run it twice

4

How do I fix this? Any help will be appreciated. Thank you

I tried the above code but didn’t work as I wanted it to work

Advertisement

Answer

I suppose you only want the small random image you generated in this iteration in your code. The problem you have, is due to the modification of your calling args.

When you call your function multiple times with the same big image

markup_image = ...
result_1 = mask_generation(blob_index=0, image_index=0)
result_2 = mask_generation(blob_index=1, image_index=0)

You get in result_2 both small images.

This is due to the writing to the original image in

experimental_image[y:y+h, x:x+w] = cropped_images[blob_index]

This adds the small image to your original image in your list of images. When getting this image the next time, the small image is already there.

To fix:

  • Do not alter your images, e.g. by first copying the image and then adding the small image in your function
  • Probably even better: Only give your function a big and small image, and make sure that they always receive a copy
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement