Skip to content

Instantly share code, notes, and snippets.

@aryamansharda
Created January 9, 2021 23:13
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/4cd5808c314a31561badd99b52c46d7e to your computer and use it in GitHub Desktop.
Save aryamansharda/4cd5808c314a31561badd99b52c46d7e to your computer and use it in GitHub Desktop.
Histogram Equalization
from PIL import Image
# Converts image to grayscale
inputImage = Image.open("source.png").convert('L')
outputImage = Image.new('L', inputImage.size)
width, height = inputImage.size
frequency = {}
# There's simpler ways of writing the following code, but I'm prioritizng clarity over brevity
# Fill the frequency count with 0s
for intensity in range(256):
frequency[intensity] = 0
# Count how frequently an intensity level appears in the input image
for x in range(width):
for y in range(height):
intensity = inputImage.getpixel((x,y))
if (intensity in frequency):
frequency[intensity] += 1
else:
frequency[intensity] = 1
intensityFrequencies = [frequency[key] for key in sorted(frequency.keys())]
cummulativeSum = 0
index = 0
cdf = []
for intensityFrequency in intensityFrequencies:
cummulativeSum += intensityFrequency
cdf.append(cummulativeSum)
index += 1
# Now we need to normalize the CDF to fit between a range of [0, 255]
# We use the values in the CDF to change the intensity of pixels in the original image so we need our intensity values to be normalized to [0,255]
minCDF = cdf[0]
maxCDF = cdf[-1]
normalizedCDF = []
for value in cdf:
# Reminder: We need to multiply by 255 as normalization gives us a value between 0 and 1
normalizedCDF.append(((value - minCDF) * 255) / (maxCDF - minCDF))
print(normalizedCDF)
print(len(normalizedCDF))
for x in range(width):
for y in range(height):
intensity = inputImage.getpixel((x,y))
outputPixel = int(normalizedCDF[intensity])
outputImage.putpixel((x,y), outputPixel)
outputImage.save('histogramEqualization.jpg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment