Python sorts images by the creation time in the exif information,
This example describes how python sorts images by the creation time in the exif information. Share it with you for your reference. The specific analysis is as follows:
We often take photos from different devices, such as cameras, mobile phones, and iPhones. The operating system records the creation date, which is often changed due to copying and other reasons, the following code sorts images by the creation time in exif, which is very useful.
Copy codeThe Code is as follows:
Import OS
Import shutil
Import Image
From PIL. ExifTags import TAGS
Def print_all_known_exif_tags ():
For k in sorted (TAGS ):
Print k, TAGS [k]
Def print_all_exif_tags (image ):
Try:
Img = Image. open (image)
Except t Exception, e:
Print image, "skipping due to", e
Else:
Xf = img. _ getexif ()
For tag in xf:
Print TAGS. get (tag), xf [tag]
Finally:
Print 'done'
Def get_minimum_creation_time (exif_data ):
Mtime = "? "
If 306 in exif_data and exif_data [306] <mtime: #306 = DateTime
Mtime = exif_data [306]
If 36867 in exif_data and exif_data [36867] <mtime: #36867 = DateTimeOriginal
Mtime = exif_data [36867]
If 36868 in exif_data and exif_data [36868] <mtime: #36868 = DateTimeDigitized
Mtime = exif_data [36868]
Return mtime
Def get_creationdate_with_filename_as_dict (list_of_folders ):
Print "Processing all image files in :"
Result = {}
For folder in list_of_folders:
Print "-" + folder
Counter = 0
For f in OS. listdir (folder ):
Counter + = 1
FullFileName = folder + "\" + f
Try:
Img = Image. open (fullFileName)
Except t Exception, e:
Print "Skipping '% s' due to exception: % s" % (f, e)
Continue
Mtime = get_minimum_creation_time (img. _ getexif ())
I = 0
While mtime + "_" * I in result:
I + = 1
Mtime = mtime + "_" * I
Result [mtime] = fullFileName
Print "Found % s orignal files in % s." % (counter, folder)
Print "Added total of % s to dictionary." % len (result)
Return result
Def copy_from_image_dict_to_directory (image_dict, output_dir ):
Assert OS. path. exists (output_dir)
For I, key in enumerate (sorted (image_dict )):
Dummy, extension = OS. path. splitext (image_dict [key])
New_file_name = key. replace (":", "-") + extension
Output_file = output_dir + new_file_name
Shutil. copy2 (image_dict [key], output_file)
Print "Copied % s files to % s" % (I + 1, output_dir)
If _ name __= = "_ main __":
Source_dir = "/var/tmp/images"
Output_dir = "/var/tmp/output"
# Obtain/var/tmp/images/iPhone,/var/tmp/images/CanonPowerShot,/var/tmp/images/Nikon1
List_of_folders = [source_dir + subfolder for subfolder in OS. listdir (source_dir)]
All_files = get_creationdate_with_filename_as_dict (list_of_folders)
Copy_from_image_dict_to_directory (all_files, output_dir)
I hope this article will help you with Python programming.