Clean single image histogram
Source: https://www.codespeedy.com/plot-a-histogram-for-an-image-in-pil-python/
This commit is contained in:
		| @@ -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() | ||||
		Reference in New Issue
	
	Block a user