From 5c1f346f2ea4bb15f62042750caa2ae2def7c5ac Mon Sep 17 00:00:00 2001 From: Benjamin Loison Date: Thu, 25 Apr 2024 14:16:58 +0200 Subject: [PATCH] Clean single image histogram Source: https://www.codespeedy.com/plot-a-histogram-for-an-image-in-pil-python/ --- datasets/raise/generate_histogram.py | 48 +++++++++++++++++----------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/datasets/raise/generate_histogram.py b/datasets/raise/generate_histogram.py index 5d589c3..b678218 100644 --- a/datasets/raise/generate_histogram.py +++ b/datasets/raise/generate_histogram.py @@ -1,27 +1,39 @@ import os from PIL import Image -import matplotlib.pyplot as plot +import matplotlib.pyplot as plt +import numpy as np +from tqdm import tqdm os.chdir('/home/benjamin/Desktop/bens_folder/school/ens/asp/aria/internship/work/datasets/raise/flat-field/TIF') -image = Image.open('flat_001.tif') -image.histogram() - -HEX_COLOR = '#%02x%02x%02x' - -def getColor(intensity, colorIndex): - return HEX_COLOR % tuple((intensity if colorIndex == colorIndexTmp else 0) for colorIndexTmp in range(3)) - -histogram = image.histogram() - +NUMBER_OF_COLORS = 3 +HEX_COLOR = '#' + '%02x' * NUMBER_OF_COLORS COLOR_BASE = 256 -red = histogram[0:COLOR_BASE] -green = histogram[COLOR_BASE:COLOR_BASE*2] -blue = histogram[COLOR_BASE*2:COLOR_BASE*3] -for colorIndex, color in enumerate([red, green, blue]): - #plt.figure(colorIndex) - for i in range(COLOR_BASE): - plt.bar(i, color[i], color = getColor(i, colorIndex), alpha = 0.3) +def getColor(colorIntensity, colorIndex): + return HEX_COLOR % tuple((colorIntensity if colorIndex == colorIndexTmp else 0) for colorIndexTmp in range(NUMBER_OF_COLORS)) + +def getHistogram(fileName): + image = Image.open(fileName) + + histogram = image.histogram() + + colors = [histogram[COLOR_BASE * colorIndex:COLOR_BASE * (colorIndex + 1)] for colorIndex in range(NUMBER_OF_COLORS)] + return colors + +def plotHistogram(colors): + for colorIndex, color in enumerate(colors): + for colorIntensity in range(COLOR_BASE): + plt.bar(colorIntensity, color[colorIntensity], color = getColor(colorIntensity, colorIndex), alpha = 0.3) + +fileNameColors = [] + +for fileName in tqdm(os.listdir()): + colors = getHistogram(fileName) + fileNameColors += [colors] + +meanFileNameColors = np.mean(fileNameColors, axis = 0) + +plotHistogram(meanFileNameColors) plt.show() \ No newline at end of file