Skip to content

Instantly share code, notes, and snippets.

@acgotaku
Created October 5, 2015 14:21
Show Gist options
  • Save acgotaku/9c3b060d6e1de8751581 to your computer and use it in GitHub Desktop.
Save acgotaku/9c3b060d6e1de8751581 to your computer and use it in GitHub Desktop.
Histogram_equalization
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
import os
import sys
from PIL import Image
import numpy as np
def read(imgPath):
img = Image.open(imgPath)
img = img.convert("L")
pix = img.load()
value = img.histogram()
cumulative = np.cumsum(value)
min=0
for index in range(0,img.size[1]):
if(cumulative[index]>0):
min=cumulative[index]
break
pixdata={}
for index in range(0,256):
data=convert(cumulative,index,min,img.size[0],img.size[1])
pixdata[index]=data
for y in range(0,img.size[1]):
for x in range(0,img.size[0]):
temp=pix[x,y]
pix[x,y]=pixdata[temp]
img.save(os.path.dirname(os.path.abspath(imgPath))+os.sep+"new_"+os.path.basename(os.path.abspath(imgPath)))
print("new_"+os.path.basename(os.path.abspath(imgPath)) +" file is generated!")
def convert(cumulative,index,min,M,N,L=256):
result=round((cumulative[index]-min)/((M*N)-min)*(L-1))
return int(result)
def main(argv):
args = argv[1]
read(args)
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment