|
| 1 | +--- |
| 2 | +Title: '.frombuffer()' |
| 3 | +Description: 'Creates an image memory from a bytes or buffer object containing raw pixel data.' |
| 4 | +Subjects: |
| 5 | + - 'Data Visualization' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Data' |
| 9 | + - 'Images' |
| 10 | + - 'Libraries' |
| 11 | + - 'Pillow' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/data-science' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`.frombuffer()`** method in the Pillow Image module creates an image memory from a bytes or buffer object containing raw pixel data. It provides a powerful way to create Image objects directly from binary data without reading from a file. This method is particularly useful when working with image data generated in memory, data received from network connections, or when interfacing with other libraries that produce raw pixel data like NumPy arrays. |
| 18 | + |
| 19 | +`.frombuffer()` enables efficient manipulation of image data by avoiding unnecessary file I/O operations, making it ideal for applications requiring high-performance image processing, computer vision tasks, or when generating images procedurally. |
| 20 | + |
| 21 | +## Syntax |
| 22 | + |
| 23 | +```pseudo |
| 24 | +PIL.Image.frombuffer(mode, size, data, decoder_name='raw', *args) |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `mode`: The image mode. Common values include `'RGB'`, `'RGBA'`, `'L'` (for grayscale), etc. This defines how the bytes in the buffer should be interpreted. |
| 30 | +- `size`: A tuple of `(width, height)` defining the dimensions of the image. |
| 31 | +- `data`: A bytes or buffer object containing the raw pixel data. |
| 32 | +- `decoder_name`: The decoder to use. Default is `'raw'`. |
| 33 | +- `*args`: Additional arguments to pass to the decoder. |
| 34 | + |
| 35 | +**Return value:** |
| 36 | + |
| 37 | +The `.frombuffer()` method returns an `Image` object. |
| 38 | + |
| 39 | +## Example 1: Creating an Image from Raw RGB Data |
| 40 | + |
| 41 | +This example demonstrates how to create an image from raw RGB pixel data stored in a bytes object. Each pixel requires 3 bytes (one for each color channel), so the total buffer size should match width × height × 3. Here is the code: |
| 42 | + |
| 43 | +```py |
| 44 | +from PIL import Image |
| 45 | +import numpy as np |
| 46 | + |
| 47 | +# Create some sample data - a gradient from black to red |
| 48 | +width, height = 256, 100 |
| 49 | +data = bytearray() |
| 50 | +for y in range(height): |
| 51 | + for x in range(width): |
| 52 | + # Red channel increases with x position |
| 53 | + data.extend([x, 0, 0]) # R, G, B values |
| 54 | + |
| 55 | +# Create image from the raw buffer data |
| 56 | +image = Image.frombuffer('RGB', (width, height), bytes(data)) |
| 57 | + |
| 58 | +# Save the result |
| 59 | +image.save('red_gradient.png') |
| 60 | +# Display the image |
| 61 | +image.show() |
| 62 | +``` |
| 63 | + |
| 64 | +It produces the output as follows: |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | +This code generates an image with a horizontal gradient from black to red, demonstrating how to directly create an image from raw pixel data in memory. |
| 69 | + |
| 70 | +## Example 2: Converting NumPy Arrays to Pillow Images |
| 71 | + |
| 72 | +This example shows a common real-world use case where `.frombuffer()` is used to efficiently convert a NumPy array to a Pillow Image without copying the underlying data: |
| 73 | + |
| 74 | +```py |
| 75 | +from PIL import Image |
| 76 | +import numpy as np |
| 77 | + |
| 78 | +# Create a NumPy array with some image data |
| 79 | +# Generate a gradient with NumPy (more efficient than the previous example) |
| 80 | +width, height = 256, 100 |
| 81 | +array = np.zeros((height, width, 3), dtype=np.uint8) |
| 82 | +array[:, :, 0] = np.linspace(0, 255, width) # Red channel |
| 83 | +array[:, :, 1] = np.linspace(0, 255, height)[:, np.newaxis] # Green channel |
| 84 | + |
| 85 | +# Convert NumPy array to Pillow Image with frombuffer() |
| 86 | +# Note: We need to ensure the array is contiguous in memory |
| 87 | +if not array.flags.contiguous: |
| 88 | + array = np.ascontiguousarray(array) |
| 89 | + |
| 90 | +# Create image from buffer |
| 91 | +image = Image.frombuffer('RGB', (width, height), array, 'raw', 'RGB', 0, 1) |
| 92 | + |
| 93 | +# Save the result |
| 94 | +image.save('numpy_gradient.png') |
| 95 | +# Display the image |
| 96 | +image.show() |
| 97 | +``` |
| 98 | + |
| 99 | +It produces the output as follows: |
| 100 | + |
| 101 | + |
| 102 | + |
| 103 | +This demonstrates how to convert a NumPy array to a Pillow Image efficiently, creating a gradient that transitions from black to yellow (combination of red and green channels). |
| 104 | + |
| 105 | +## Example 3: Processing Image Data from External Sources |
| 106 | + |
| 107 | +This example illustrates how to use `.frombuffer()` when receiving raw image data from an external source, such as a web API or a binary file: |
| 108 | + |
| 109 | +```py |
| 110 | +from PIL import Image |
| 111 | +import requests |
| 112 | +import io |
| 113 | +import struct |
| 114 | + |
| 115 | +# Function to read raw image data from a binary file |
| 116 | +def read_raw_image(filename, width, height, mode='RGB'): |
| 117 | + with open(filename, 'rb') as f: |
| 118 | + raw_data = f.read() |
| 119 | + |
| 120 | + # Create image from raw data |
| 121 | + return Image.frombuffer(mode, (width, height), raw_data) |
| 122 | + |
| 123 | +# Example: Generate a simple raw file with RGB data |
| 124 | +def create_sample_raw_file(filename, width, height): |
| 125 | + # Create a checkerboard pattern |
| 126 | + with open(filename, 'wb') as f: |
| 127 | + for y in range(height): |
| 128 | + for x in range(width): |
| 129 | + # Create a checkerboard pattern (black and white) |
| 130 | + if (x + y) % 2 == 0: |
| 131 | + f.write(struct.pack('BBB', 255, 255, 255)) # White pixel |
| 132 | + else: |
| 133 | + f.write(struct.pack('BBB', 0, 0, 0)) # Black pixel |
| 134 | + |
| 135 | +# Create a sample raw file |
| 136 | +width, height = 100, 100 |
| 137 | +raw_filename = 'checkerboard.raw' |
| 138 | +create_sample_raw_file(raw_filename, width, height) |
| 139 | + |
| 140 | +# Read and display the raw image data |
| 141 | +image = read_raw_image(raw_filename, width, height, 'RGB') |
| 142 | +image.save('checkerboard.png') |
| 143 | +image.show() |
| 144 | +``` |
| 145 | + |
| 146 | +It produces the output as follows: |
| 147 | + |
| 148 | + |
| 149 | + |
| 150 | +This example demonstrates reading raw image data from a binary file, which is similar to processing raw image data received from external sources or hardware devices. |
0 commit comments