How to apply image thresholding in Python with NumPy

Learn how to apply a threshold to images in Python with numpy and Pillow.


Learn how to apply a threshold to images in Python with numpy and Pillow.

This snippet loads an image, applies a threshold, and then saves a new binarized image with only black and white pixels.

import numpy as np
from PIL import Image


threshold = 100

img = Image.open('img_gray.png') 
# Note, if you load a color image, also apply img.convert('L')

img_np = np.array(img)
img_np = np.where(img_np > threshold, 255, 0)

img.putdata(img_np.flatten())

img.save('img_thresholded.png')

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏