Adjusting contrast of image purely with numpy

后端 未结 3 1930
庸人自扰
庸人自扰 2021-01-22 20:30

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 nu         


        
3条回答
  •  不要未来只要你来
    2021-01-22 21:17

    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')
    

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

提交回复
热议问题