Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting contrast of image purely with numpy

I am trying write a contrast adjustment for images in gray scale colors but couldn't find the right way to do it so far. This is what I came up with:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from scipy import misc
def fix_contrast(image):
    minimumColor = np.amin(image)
    maximumColor = np.amax(image)
    #avg = (minimumColor - maximumColor)/2 first attempt
    avg = np.mean(image) #second attempt
    colorDownMatrix = image < avg # also tried
    colorUpMatrix = image > avg 
    #also tried:   colorUpMatrix = image > avg * 1.2
    # and : colorDownMatrix = image < avg* 0.3

    image = image - minimumColor*colorDownMatrix
    image = image + maximumColor*colorUpMatrix
    lessThen0 = image<0
    moreThen255 = image>255
    image[lessThen0] = 0
    image[moreThen255] = 255
    return image    

My general attempt was to decrease elements towards 0 the pixels that their are "closer" to 0 and to increase elements towards 255 the elements that are "closer" to 255. I tried to measure closeness by mean function but before that by the arithmetic average, but all my attempts didn't get me to any good result.

the image I am working on : enter image description here

the result I am aiming for: goal picture

Am I anywhere close to the solution? Any hints/ tips will be great

like image 905
barshopen Avatar asked Dec 03 '22 20:12

barshopen


1 Answers

I'm learning Python and numpy and thought I'd try to implement a "LookUp Table" (LUT). It works, and the output image has the full range from black to white, but I'm happy to receive suggestions for improvement.

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Open the input image as numpy array, convert to greyscale and drop alpha
npImage=np.array(Image.open("cartoon.png").convert("L"))

# Get brightness range - i.e. darkest and lightest pixels
min=np.min(npImage)        # result=144
max=np.max(npImage)        # result=216

# Make a LUT (Look-Up Table) to translate image values
LUT=np.zeros(256,dtype=np.uint8)
LUT[min:max+1]=np.linspace(start=0,stop=255,num=(max-min)+1,endpoint=True,dtype=np.uint8)

# Apply LUT and save resulting image
Image.fromarray(LUT[npImage]).save('result.png')

enter image description here

Keywords: Python, Numpy, PIL, Pillow, image, image processing, LUT, Look-Up Table, Lookup, contrast, stretch.

like image 140
Mark Setchell Avatar answered Dec 06 '22 09:12

Mark Setchell