Last active
June 10, 2019 20:06
-
-
Save kupp1/f34748ca0a3e87b331484888692badec to your computer and use it in GitHub Desktop.
Python pretty image histogram with cdf
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
import numpy | |
import sys | |
from PIL import Image | |
import matplotlib.pyplot as plt | |
def get_rgb(r: int, g: int, b: int): | |
if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255: | |
return '#%02x%02x%02x' % (r, g, b) | |
try: | |
image_path = sys.argv[1] | |
except IndexError: | |
print('USAGE: python3 hist.py [image path]') | |
sys.exit() | |
image = Image.open(image_path) | |
image = image.convert('RGB') | |
r, g, b = image.split() | |
fig = plt.figure() | |
hist_ax = fig.add_subplot(111) | |
cdf_ax = fig.add_subplot(111, frame_on=False) | |
for i, value in enumerate(r.histogram()): | |
color = get_rgb(i, 0, 0) | |
hist_ax.bar(i, value, color=color, edgecolor=color, alpha=0.3) | |
cdf = numpy.array(r.histogram()).cumsum() | |
cdf_ax.plot([x for x in range(256)], list(cdf), 'r--') | |
for i, value in enumerate(g.histogram()): | |
color = get_rgb(0, i, 0) | |
hist_ax.bar(i, value, color=color, edgecolor=color, alpha=0.3) | |
cdf = numpy.array(g.histogram()).cumsum() | |
cdf_ax.plot([x for x in range(256)], list(cdf), 'g--') | |
for i, value in enumerate(b.histogram()): | |
color = get_rgb(0, 0, i) | |
hist_ax.bar(i, value, color=color, edgecolor=color, alpha=0.3) | |
cdf = numpy.array(b.histogram()).cumsum() | |
cdf_ax.plot([x for x in range(256)], list(cdf), 'b--') | |
cdf_ax.yaxis.tick_right() | |
cdf_ax.yaxis.set_label_position('right') | |
cdf_ax.set_ylabel('cdf y', fontsize=15, color='C1') | |
hist_ax.set_ylabel('hist y', fontsize=15, color='C3') | |
cdf_ax.set_xticks([]) | |
hist_ax.set_xticks([0, 50, 100, 150, 200, 255]) | |
plt.title('histogram of %s' % image_path, fontsize=24) | |
plt.savefig('hist.png', bbox_inches='tight') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment