kee
kee

Reputation: 11619

Python Image/Pillow: How to make the background more white of images

I have images like these:

enter image description here enter image description here

What I would like to do is to make the background of the image more white so that the letters are more visible. Here is a good image from my perspective:

enter image description here

I am using Pillow in Python.

Upvotes: 1

Views: 1894

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

The simplest is probably to use ImageOps.autocontrast() to increase the contrast like this:

from PIL import Image, ImageOps

# Open image as greyscale
im = Image.open('letter.png').convert('L')

# Autocontrast
result = ImageOps.autocontrast(im) 

# Save
result.save('result.png')

enter image description here


A more sophisticated approach would be to use an Otsu thresholding to split the pixels optimally into 2 colours, but for that you would want scikit-image like this:

from skimage import filters
from skimage.io import imread, imsave

# Load image as greyscale
img = imread('letter.png', as_gray=True)

# Get Otsu threshold - result is 151
threshold = filters.threshold_otsu(img) 

enter image description here

You can now either continue and make all pixels above the threshold white and leave those below as they are:

img[img>threshold] = 255
imsave('result.png',img)

enter image description here

Or, you can do a complete threshold where all pixels end up either solid black or solid white:

result = (img>threshold).astype(np.uint8) * 255 
imsave('result.png',result)

enter image description here

Upvotes: 2

Related Questions