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*


PySaaS: The Pure Python SaaS Starter Kit

🚀 Build a software business faster with pure Python: Link*

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