Created
June 7, 2013 11:27
-
-
Save iamsilvio/5728643 to your computer and use it in GitHub Desktop.
dirty python script using PIL to remove black pictures from a Folder and tag each picture with a date string from file name!
I have used It one time for 60.000 jpg and it works fine. Please do not use this code as a sample of good python code :)
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
from shutil import move | |
import os | |
from sys import stdout | |
from datetime import datetime | |
from time import time | |
from PIL import ImageFont, Image, ImageDraw | |
img_number = 1 | |
black_images = 0 | |
root_in = "T:\\cz\\ftproot\\" | |
root_out = "T:\\cz\\out\\" | |
error_out = "T:\\cz\\black_out\\" | |
def _write_time_and_save(src, text): | |
global img_number | |
global black_images | |
font = ImageFont.truetype("C:\\Windows\\Fonts\\Ubuntu-L.ttf", 18) | |
img = Image.open(src) | |
width, height = img.size | |
pixels = img.load() | |
data = [] | |
for x in range(width): | |
for y in range(height): | |
cpixel = pixels[x, y] | |
data.append(cpixel) | |
r = 0 | |
g = 0 | |
b = 0 | |
counter = 0 | |
for x in range(len(data)): | |
r += data[x][0] | |
g += data[x][1] | |
b += data[x][2] | |
counter += 1 | |
rAvg = r / counter | |
gAvg = g / counter | |
bAvg = b / counter | |
if rAvg > 40 and gAvg > 40 and bAvg > 40: | |
draw = ImageDraw.Draw(img) | |
draw.text((20, 20), text, (0, 0, 0), font=font) | |
dest = os.path.join(root_out, str(img_number) + ".jpg") | |
img.save(dest) | |
img_number += 1 | |
else: | |
move(src, os.path.join(error_out, os.path.basename(src))) | |
black_images += 1 | |
fl = [f for f in os.listdir(root_in) if | |
os.path.isfile(os.path.join(root_in, f))] | |
if not os.path.exists(root_out): | |
os.makedirs(root_out) | |
av_time = None | |
for f in fl: | |
start_time = time() | |
dateString = datetime.strptime(f[4:-7], '%y-%m-%d_%H-%M-%S').strftime( | |
"%Y-%m-%d %H:%M:%S") | |
_write_time_and_save(os.path.join(root_in, f), dateString) | |
elapsed_time = time() - start_time | |
if av_time: | |
av_time = (av_time + elapsed_time) / 2 | |
else: | |
av_time = elapsed_time | |
img_done = img_number + black_images | |
stdout.write("\r%d (black: %d good: %d) of %d | time: %s (%s)" % ( | |
img_done, black_images, img_number, len(fl), av_time * img_done, | |
av_time * (len(fl) - img_done))) | |
stdout.flush() | |
stdout.write("\n") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requires pillow
compiled version for win32 can be found at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow
the font I used at line 20
http://font.ubuntu.com/