Skip to content

Commit b4bfe08

Browse files
[Term Entry] Python Pillow - Image: .eval() (Codecademy#6405)
* Initial commit for eval * Add eval concept * Update the parameters * Fix formatting * Update eval.md * minor fixes in code for RGB images ---------
1 parent 8766374 commit b4bfe08

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
Title: '.eval()'
3+
Description: 'Applies a function to each pixel of an image, returning a new image with modified pixel values.'
4+
Subjects:
5+
- 'Computer science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Computer Vision'
9+
- 'Images'
10+
- 'Pillow'
11+
- 'Values'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`.eval()`** method in Pillow processes an image by applying a given function to each pixel. This is useful for pixel-level transformations like adjusting brightness, inverting colors, or applying custom filters.
18+
19+
## Syntax
20+
21+
```pseudo
22+
Image.eval(image, function)
23+
```
24+
25+
- `image`: The input image object to process.
26+
- `function`: A function/lambda that takes one integer argument (the pixel value) and returns a modified integer.
27+
28+
## Example
29+
30+
The example below converts the input image into a new image, where each pixel is transformed by a function:
31+
32+
```py
33+
from PIL import Image
34+
35+
# Open an image
36+
img = Image.open('media/pillow-original.jpeg').convert("RGB") # Ensure RGB mode
37+
38+
# Define a function to invert pixel values
39+
def invert_pixel(x):
40+
return 255 - x # Works for grayscale and individual RGB channels
41+
42+
# Apply the function to each pixel
43+
new_img = Image.eval(img, invert_pixel)
44+
45+
# Display the new image
46+
new_img.show()
47+
```
48+
49+
In this example:
50+
51+
- `x`: Represents the pixel intensity value, which typically ranges from 0-255 (for 8-bit grayscale or RGB images).
52+
- `255 - x`: Subtracts the pixel value from 255, effectively inverting its brightness: 0 → 255 (pure black becomes pure white), 255 → 0 (pure white becomes pure black), 100 → 155 (mid-gray becomes a lighter gray).
53+
54+
Here is the original image:
55+
56+
![Original Image](https://raw.githubusercontent.com/Codecademy/docs/main/media/pillow-original.jpeg)
57+
58+
Here is the updated image:
59+
60+
![Updated Image](https://raw.githubusercontent.com/Codecademy/docs/main/media/pillow-eval.png)

media/pillow-eval.png

1010 KB
Loading

0 commit comments

Comments
 (0)