Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# See LICENSE.txt file for licensing information
# See CHANGES.txt file for all contributors and changes
#
"""
Runs Exif tag extraction in command line.
"""
import sys
import getopt
import logging
import timeit
from exifread.tags import DEFAULT_STOP_TAG, FIELD_TYPES
from exifread import process_file, exif_log, __version__
logger = exif_log.get_logger()
def usage(exit_status):
"""Show command line usage."""
msg = ('Usage: EXIF.py [OPTIONS] file1 [file2 ...]\n'
'Extract EXIF information from digital camera image files.\n\nOptions:\n'
'-h --help Display usage information and exit.\n'
'-v --version Display version information and exit.\n'
'-q --quick Do not process MakerNotes.\n'
'-t TAG --stop-tag TAG Stop processing when this tag is retrieved.\n'
'-s --strict Run in strict mode (stop on errors).\n'
'-d --debug Run in debug mode (display extra info).\n'
'-c --color Output in color (only works with debug on POSIX).\n'
)
print(msg)
sys.exit(exit_status)
def show_version():
"""Show the program version."""
print('Version %s on Python%s' % (__version__, sys.version_info[0]))
sys.exit(0)
def all_tags(path) -> {str: str}:
"""Method to return Exif tags"""
file = open(path, "rb")
tags = exifread.process_file(file, details=False)
return tags
def is_rotated(fp):
"""Fast version of read_exif(fp).is_rotated, using an exif header subset."""
exif = exifread.process_file(fp, stop_tag='Orientation', details=False)
return EXIFInfo(exif).is_rotated
filename (str): Name of the file
Returns:
np array: Image
float: Rescale ratio
"""
img = cv2.imread(file_name)
if img.shape[2] == 4 :
img = img[:,:,:3]
if img.shape[2] == 1 :
img = np.repeat(img, 3, axis = 2)
ftest = open(file_name, 'rb')
tags = exifread.process_file(ftest)
try:
if str(tags['Thumbnail Orientation']) == 'Rotated 90 CW':
img = cv2.transpose(img)
img = cv2.flip(img, 1)
elif str(tags['Thumbnail Orientation']) == 'Rotated 90 CCW':
img = cv2.transpose(img)
img = cv2.flip(img, 0)
elif str(tags['Thumbnail Orientation']) == 'Rotated 180':
img = cv2.flip(img, -1)
except:
tags = tags
ratio = 1.0
if img.shape[0]*img.shape[1]>1024*768:
ratio = (1024*768/float(img.shape[0]*img.shape[1]))**(0.5)
else:
print "\t-" + dc[0][0]
print "\t-" + dc[0][1]
for key, value in dc[0][2].items():
if color_mode:
cprint("\t-" + key + ": ", "cyan", end="")
cprint(str(value))
else:
print "\t-" + key + ": " + str(value)
# Print EXIF metadata
if color_mode: print("\n\t-----EXIF METADATA-----", "cyan")
else: "\n\t-----EXIF METADATA-----"
tags = exifread.process_file(image)
for tag in tags.keys():
if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename', 'EXIF MakerNote'):
if color_mode:
cprint("\t-" + str(tag) + ": ", "cyan", end="")
cprint(str(tags[tag]))
else:
print "\t-" + str(tag) + ": " + str(tags[tag])
def get_exif(filename):
try:
with open(filename, 'rb') as f:
return exifread.process_file(f)
except:
return
def _extract_exif(self):
ret = {}
# ipdb.set_trace()
i = PIL.Image.open(self.image_path)
info = i._getexif()
date_format = "%Y:%m:%d %H:%M:%S"
if info:
for tag, value in info.items():
decoded = EXIFTAGS.get(tag, tag)
ret[decoded] = value
with open(self.image_path, 'rb') as fimg:
exif = exifread.process_file(fimg, details=False)
serializable = dict(
[key, value.printable] for key, value in exif.items())
self.exif_json = serializable
# ipdb.set_trace()
if 'EXIF DateTimeOriginal' in exif.keys():
tst_str = exif['EXIF DateTimeOriginal'].values
try:
tst_dt = datetime.strptime(
tst_str, date_format).replace(tzinfo=pytz.utc)
except:
tst_dt = None
# ipdb.set_trace()
self.exif_timestamp = tst_dt
else:
self.exif_timestamp = None
def __load(self, url):
self.local_file = url
self.loader.setVisible(False)
self.pixmap = self.base.load_image(url, True)
screen_size = self.base.get_screen_size()
if (screen_size.width() - 10 < self.pixmap.width() or screen_size.height() - 10 < self.pixmap.height()):
width = min(self.pixmap.width(), screen_size.width())
height = min(self.pixmap.height(), screen_size.height())
self.pixmap = self.pixmap.scaled(QSize(screen_size.width(), screen_size.height()), Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.setFixedSize(self.pixmap.width(), self.pixmap.height())
if EXIF_SUPPORT:
fd = open(url, 'rb')
tags = exifread.process_file(fd)
if tags != {}:
data = {
'Camera': "%s %s" % (tags['Image Make'], tags['Image Model']),
'Software': '' if 'Image Software' not in tags else tags['Image Software'],
'Original Datetime': '' if 'EXIF DateTimeOriginal' not in tags else tags['EXIF DateTimeOriginal'],
'Dimensions': "%s x %s" % (tags['EXIF ExifImageWidth'], tags['EXIF ExifImageLength']),
'Copyright': '' if 'Image Copyright' not in tags else tags['Image Copyright'],
'Comment': '' if 'EXIF UserComment' not in tags else tags['EXIF UserComment']
}
exif_data = ''
for key in ['Camera', 'Software', 'Original Datetime', 'Dimensions', 'Copyright', 'Comment']:
if exif_data != '':
exif_data += ' – '
exif_data += "%s: %s" % (key, data[key])
else:
exif_data = i18n.get('exif_data_not_available')
@property
def tags(self):
if self._tags is None:
#
# Get the EXIF data
#
with open(self.path, 'rb') as f:
self._tags = exifread.process_file(f)
return self._tags