Copy & Paste Images

Alec Mills
3 min readSep 7, 2022

For my 4th blog at Flat Iron, I have been exploring how to take one image and put it on another image. This will be very useful for my capstone as I will need to create my dataset that I will be using. For the capstone I will be taking a set of drones from a dataset and putting them on a background dataset to train a neural network to classify if a drone is in the image or not. For the purpose of this blog I will be taking one image of a drone and one background image and showing you each step I took to paste one image on top of the other.

For this process we will be using Pillow and a random function. If you would like to check out Pillow (PIL). It is an imaging library that we will use to create our masks. Below will be the two imports that we will be using.

Imports

We will be using this image of a Drone.

Drone Image

This will be the Background Image that I will be placing the drone on top of.

Background Image

Looking at the image of the drone we can see that the drone has a white background and we do not want the drone to stick out with a white background on the image because then the network could learn that the white background is actually needed for a drone to be present. So we set our threshold to 245 knowing our dataset of drones all have white backgrounds. This will take everything in the image that has a pixel threshold below 245.

loading the image

To create the mask of an image you need to pass the X max and Y max into Image. We will set these values beforehand and then pass them in.

finding the bounds of the image

Pass in the size of the image to the mask, Then loop through the range to create the mask.

Creating the mask

Because the Drone is a larger image we will then resize the image because a real drone wouldn’t be that large on the image.

Here is the mask you just created after the image was resized.

Mask of the Drone

We will then create a random spot on the image that won’t place the drone outside of the image by using the bounds and we will show the image

As you can see below here is the final image with the drone pasted on top!

Final Image

I hope you enjoyed my tutorial and found it useful!

--

--