fromarray()

Published Jun 8, 2024
Contribute to Docs

.fromarray() is a function from the Image module that is used to process images for more clarity. It creates a new image derived from a specified array.

Syntax

Image.fromarray(obj_array, mode="CMYK")

.fromarray() takes two parameters:

  • obj_array: It represents a defined array
  • mode: It is an optional parameter that defines the type and depth of a pixel in the image that will be created. If mode is not used, the new image will be stored as is.

The mode parameter can take the following values:

  • CMYK: It represents the color palette made from base colors Cyan, Magenta, Yellow, and Key(black). Each color has an 8-bit pixel to store its value, which means CMYK has 4x8-bit pixels to store the values.
  • RGB: It represents the color palette made from Red, Green, and Blue colors. It has 3x8-bit pixels available to store the values.
  • L: It represents grayscale or shade of gray from white to black. It only has an 8-bit pixel to store its value.

Example

The example below shows the value of a pixel in coordinate (0,0) after the parameter mode is used with CMYK as the value.

# Import Image module from Pillow library
from PIL import Image
import numpy as np
# Defined an array 300 by 36 with 200 as all the pixel values
obj_array = np.full((300, 36), 200)
# Create an image from the array, as our `obj_array' is stored in the form of a
# numbered array
new_imageA = Image.fromarray(obj_array, mode="CMYK")
# Show the image generated using .fromarray()
new_imageA.show()
# Show the pixel value by the coordinate
print(new_imageA.getpixel((0,0)))

The result proves that the obj_array has been successfully generated as new_imageA, and the pixel at coordinate (0,0) is stored as a CMYK color combination with the values shown below.

Image generated by fromarray function

(200, 0, 0, 0)

Codebyte Example

Run the following Codebyte example to understand how a new image is created from the specified array in the RGB color format.

Code
Output
Loading...

All contributors

Looking to contribute?

Learn Python:Pillow on Codecademy