Created
January 9, 2021 23:13
-
-
Save aryamansharda/4cd5808c314a31561badd99b52c46d7e to your computer and use it in GitHub Desktop.
Histogram Equalization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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