Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Creating Images With NumPy

00:00 Using NumPy to Create Images. Having seen how to manipulate images using NumPy and Pillow, you can go further and create them from scratch. You can start by creating a grayscale image. On-screen, you’ll see how to create a simple image containing a square, but you can create more elaborate images in the same way.

00:25 You create a 600x600 array containing zeros everywhere, and then you set the value of a set of pixels at the center of the array to 255. You can index NumPy arrays using both rows and columns. In this example, the first slice of 200:400 represents the rows 200 to 399.

00:53 The second slice represents the columns 200 to 399. Once again, you use Image.fromarray() to convert the NumPy array into an object of type Image. Finally, you show the output on-screen.

01:11 You’ve created a grayscale image containing a square. The mode of the image is inferred automatically when you use Image.fromarray(). In this case, mode "F" is used, which corresponds to an image with 32-bit floating-point pixels.

01:27 It’s easy to convert this into a simpler grayscale image with 8-bit pixels.

01:37 You can go further and create a color image. The process is repeated to create three images: one corresponding to the red, one to the green, and a final one corresponding to the blue channel. Once more, you create a square in each, but in different locations.

02:07 You create an Image object from each NumPy array and convert them to grayscale images using mode "L".

02:31 Now, you can combine these three separate images into one RGB image using Image.merge(). The first argument in Image.merge() is the mode of the image output.

02:44 The second argument is a sequence with the individual single-band images. Finally, you show the image on-screen. You combine the separate bands into an RGB color image.

03:01 In the next section of the course, you’ll go a step further and create an animation using NumPy and Pillow.

Become a Member to join the conversation.