Skip to content

Instantly share code, notes, and snippets.

@yassu
Last active August 29, 2015 14:17
Show Gist options
  • Save yassu/5f34dab6ff390a0f2944 to your computer and use it in GitHub Desktop.
Save yassu/5f34dab6ff390a0f2944 to your computer and use it in GitHub Desktop.
Simple analyser for Imagefiles
from os import walk
from os.path import isfile, isdir
from sys import argv
from math import sqrt
import numpy as np
from progressbar import ProgressBar, Percentage, Bar
from PIL import Image
MAX_SIZE = 1000
def get_colors(imgs):
colors = []
for img in imgs:
width, height = img.size
for x in range(width):
for y in range(height):
colors.append(img.getpixel((x, y)))
return colors
IMAGE_EXTS = ('.jpg', '.jpeg', '.png', '.gif')
def is_imgfilename(filename):
for ext in IMAGE_EXTS:
if filename.endswith(ext):
return True
return False
def glob_imgfiles(dirname):
img_filenames = []
for dpath, _, filenames in walk(dirname):
for filename in filenames:
if is_imgfilename(filename):
img_filenames.append('{}/{}'.format(dpath, filename))
if len(img_filenames) == MAX_SIZE:
return img_filenames
return img_filenames
filename = argv[1]
if isfile(filename):
filenames = [filename]
elif isdir(filename):
filenames = glob_imgfiles(filename)
else:
print('{} is not exist.'.format(filename))
quit()
widgets = ['load images: ', Percentage(), Bar()]
maxval = len(filenames) if len(filenames) < MAX_SIZE else MAX_SIZE
bar = ProgressBar(maxval=maxval, widgets=widgets).start()
try:
colors = []
for filename in filenames:
image = Image.open(filename)
colors.append(np.array(get_colors([image])))
bar.update(bar.currval + 1)
bar.finish()
except MemoryError:
print('Memory Error is raised. len of colors: {}'.format(len(colors)))
numth_colors = lambda j: [color[j] for color in colors]
mean = (np.average(numth_colors(0)), np.average(numth_colors(1)),
np.average(numth_colors(2)))
norm_mean = sqrt(mean[0] * mean[0] + mean[1] * mean[1] + mean[2] * mean[2])
std = (np.std(numth_colors(0)), np.std(numth_colors(1)),
np.std(numth_colors(2)))
print('pixel mean:', mean)
print('pixed norm mean: ', norm_mean)
print('pixel stddev:', std)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment