Skip to content

Instantly share code, notes, and snippets.

@aryamansharda
Created January 9, 2021 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aryamansharda/7d2ed03d0314104f30e1f6fe916dd6c3 to your computer and use it in GitHub Desktop.
Save aryamansharda/7d2ed03d0314104f30e1f6fe916dd6c3 to your computer and use it in GitHub Desktop.
Contrast Stretching
from PIL import Image
# Converts image to grayscale
inputImage = Image.open("source.jpg").convert('L')
outputImage = Image.new('L', inputImage.size)
width, height = inputImage.size
# We first need to find the minimum and maximum pixel intensities
minIntensity = 255
maxInsenity = 0
for x in range(width):
for y in range(height):
intensity = inputImage.getpixel((x,y))
minIntensity = min(minIntensity, intensity)
maxInsenity = max(maxInsenity, intensity)
print("Minimum Pixel Intensity: " + str(minIntensity))
print("Maximum Pixel Intensity: " + str(maxInsenity))
# Now, we'll go through the image again and update all of the pixel values to their new
# position on the scaled histogram
for x in range(width):
for y in range(height):
intensity = inputImage.getpixel((x,y))
# This normalization process returns an intensity from 0 - 1 so we need to multiply by 255
newIntensity = 255 * ((intensity - minIntensity) / (maxInsenity - minIntensity))
outputImage.putpixel((x,y), int(newIntensity))
outputImage.save('contrastStretched.jpg')
# A more sophisticated implementation would allow support for discarding the outliers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment