Long story short, I need to check an entire folder of images to see if they're grayscale. Here's a python script I just wrote that will do that, and output the results to a timestamped log file. I added some comments to explain how it works.
graycheck.py
from PIL import Image
import ImageChops
import os
import string
from time import strftime
def main():
subdir = 'C:\\pathtoimages\\'
diffdir = subdir + 'diff' # output directory if you want to save the results
badFiles = []
for subdir, dirs, files in os.walk(subdir):
if subdir != diffdir: #only check the main dir
for file in files:
if string.upper(file[-3:])=="JPG": # jpegs only
im = Image.open(file)
imGray = im.convert("L") # convert the original jpeg to grayscale and keep a copy
# need to convert back to RGB, but only if the original file wasn't already in mode L
if im.mode == "RGB":
imGray = imGray.convert("RGB")
# get the difference of the original image and the converted grayscale
# if the original was grayscale, there's no difference, so output will be entirely black
output = ImageChops.difference(imGray, im)
i = 0
for color in list(output.getdata()):
if color != (0,0,0): # check RGB black and single black value
if color != 0:
# Image is not grayscale, for we found a difference
i=i+1
print i, color
break
outputFile = diffdir + "\\" + file[:-4] + "_Diff.jpg" # output dir plus filename only plus an extension
if i==0: # image is all black, could not be blacker
badFiles.append(file)
# output.save(outputFile) # uncomment to save the results as an image - though it should be a solid black file
# print badFiles # uncomment to see the results
logfilename = strftime("%Y-%m-%d_%H-%M-%S") + ".txt"
logfile = open(logfilename, "w")
for badFile in badFiles:
logfile.write(badFile + '\n')
logfile.close()
if _name_ == '_main_':
main()
If you desire me to release this under a license, consider it released under the
MS Public License.