Created
July 3, 2023 10:04
-
-
Save nidefawl/e8053f7864e60a8a0441799f6609b8ce to your computer and use it in GitHub Desktop.
reads a image file and returns a list of tuples with the rgb values and the number of pixels with that color, sorted by the number of pixels
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
#v reads a image file and returns a list of tuples with the rgb values and the number of pixels with that color, sorted by the number of pixels | |
import sys | |
import matplotlib.pyplot as plt | |
import matplotlib.image as mpimg | |
import pprint | |
def quantize(val): | |
return val | |
def count_distinct_color_values(filepath): | |
img = mpimg.imread(filepath) | |
colors = {} | |
totalPixels = len(img) * len(img[0]) | |
n = 0 | |
for row in img: | |
for pixel in row: | |
pixel_I32 = quantize(pixel[0]) << 16 | quantize(pixel[1]) << 8 | quantize(pixel[2]) | |
if pixel_I32 in colors: | |
colors[pixel_I32] += 1 | |
else: | |
colors[pixel_I32] = 1 | |
# report progress every 100000 pixels | |
if n % 100000 == 0: | |
print('processed %d of %d pixels' % (n, totalPixels)) | |
n += 1 | |
return sorted(colors.items(), key=lambda x: x[1], reverse=True) | |
if __name__ == '__main__': | |
colorCounts = count_distinct_color_values(sys.argv[1] if len(sys.argv) > 1 else 'test.jpg') | |
# pprint.pprint(colorCounts) | |
# only print the top 10 colors | |
pprint.pprint(colorCounts[:10]) | |
# print the top 10 colors as hex values | |
pprint.pprint([(hex(color[0]), color[1]) for color in colorCounts[:10]]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment