def get_exif_geotagging(exif) -> dict: """Gets exif data related to geo coordinates.""" if not exif: raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def get_geotagging(self, exif): ''' Extract GPS Info and return ''' logging.debug("Getting GPS Info") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def get_geotagging(self, exif): geotagging = {} if not exif: #raise ValueError("No EXIF metadata found" return geotagging #geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def get_geotagging(exif): """Get GPS tags from exifs""" if not exif: raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == "GPSInfo": if idx not in exif: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def parse_exif(exif): exifData = {} if exif: for (tag, value) in exif.items(): if value: decoded_tag = TAGS.get(tag, tag) if decoded_tag != 'GPSInfo': exifData[decoded_tag] = value else: for (key, val) in GPSTAGS.items(): if key in exif[tag]: exifData[val] = exif[tag][key] # Note: GPS Latitude and Longitude are represented in true rational64u format if 'GPSLatitude' in exifData.keys() and 'GPSLongitude' in exifData.keys(): parse_coordinates(exifData) parse_location(exifData) return exifData
def get_geotagging(exif): if not exif: raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if val != "GPSLatitude" and val != "GPSLongitude": continue if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def get_geotagging(self): """ Donne les informations du TAG Exif GPS de la photo :return: Ensemble des informations GPS de la photo """ if not self.PhotoExif: #raise ValueError("No EXIF metadata found") return None geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in self.PhotoExif: #raise ValueError("No EXIF geotagging found") return None for (key, val) in GPSTAGS.items(): if key in self.PhotoExif[idx]: geotagging[val] = self.PhotoExif[idx][key] return geotagging
def get_geotagging(self, exif): """ method returns geotags information """ if not exif: raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: return geotagging for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def get_coordinates(directory, filename, exiftool): #extract only the gps data from exif mov_time = datetime.datetime.now() if filename.lower().endswith( ".mov"): #we got a movie on our hands, can't use pillow print("using exiftool on ", filename) # result = subprocess.run(['exiftool', '-GPSLatitude#', os.path.join(directory,filename)], stdout=subprocess.PIPE) result = exiftool.get_metadata(os.path.join(directory, filename)) latitude = result.get('Composite:GPSLatitude', 0) longitude = result.get('Composite:GPSLongitude', 0) date = result.get('QuickTime:CreateDate', '') mov_time1 = datetime.datetime.now() print("movie processing: ", (mov_time1 - mov_time).total_seconds()) return {'coords': (latitude, longitude), 'date': date} else: #get exif image = Image.open(os.path.join(directory, filename)) image.verify() exif = image._getexif() if not exif: print("No EXIF metadata found found. Skipping ", filename) return {'coords': (0, 0), 'date': ''} #get geotagging geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: print("No EXIF geotagging found. Skipping ", filename) return {'coords': (0, 0), 'date': ''} for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] if tag == 'DateTimeOriginal': if idx not in exif: print("No EXIF Date found.") date = '' else: date = exif[idx] img_time = datetime.datetime.now() print("image processing: ", (img_time - mov_time).total_seconds()) return {'coords': get_coords_from_geotag(geotagging), 'date': date}
def get_geotagging(exif): logger.info('get_geotagging STARTED') if not exif: logger.info('No EXIF metadata found') raise UnprocessableEntityError('No EXIF metadata found') geotagging = {} gps_info = exif.get('GPSInfo', None) if gps_info is None: logger.info('No EXIF geotagging found') raise UnprocessableEntityError('No EXIF geotagging found') for (key, val) in GPSTAGS.items(): if gps_info.get(key, None) != None: geotagging[val] = gps_info[key] logger.info(f'geo_tagging success. Retuning {geotagging}') return geotagging
def get_GPS(self, img): location = "" geoaxis = {} geotags = {} try: exif = img._getexif() for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx in exif: for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotags[val] = exif[idx][key] for axis in ["Latitude", "Longitude"]: dms = geotags[f'GPS{axis}'] ref = geotags[f'GPS{axis}Ref'] degrees = dms[0][0] / dms[0][1] minutes = dms[1][0] / dms[1][1] / 60.0 seconds = dms[2][0] / dms[2][1] / 3600.0 if ref in ['S', 'W']: degrees = -degrees minutes = -minutes seconds = -seconds geoaxis[axis] = round(degrees + minutes + seconds, 5) location = \ self.geolocator.reverse("{}, {}".format(geoaxis["Latitude"], geoaxis["Longitude"])).raw[ "address"] except Exception: return "" else: if location: location = sanitize_location(location) if not location: return "" return f'{location["town"]}, {location["country"]}' else: return ""
def get_coordinates(directory, filename): #extract only the gps data from exif mov_time = datetime.datetime.now() if filename.lower().endswith( ".mov"): #we got a movie on our hands, can't use pillow print("using exiftool on %s", filename) result = subprocess.run( ['exiftool', '-GPSLatitude#', os.path.join(directory, filename)], stdout=subprocess.PIPE) if (result.stdout.decode('utf-8') == ''): return (0, 0) latitude = float(result.stdout.decode('utf-8').split(": ")[1]) result = subprocess.run( ['exiftool', '-GPSLongitude#', os.path.join(directory, filename)], stdout=subprocess.PIPE) longitude = float(result.stdout.decode('utf-8').split(": ")[1]) mov_time1 = datetime.datetime.now() print("movie processing: %s", (mov_time1 - mov_time).total_seconds()) return (latitude, longitude) else: #get exif image = Image.open(os.path.join(directory, filename)) image.verify() exif = image._getexif() if not exif: print("No EXIF metadata found found. Skipping %s", filename) return (0, 0) #get geotagging geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: print("No EXIF geotagging found. Skipping %s", filename) return (0, 0) for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] img_time = datetime.datetime.now() print("image processing: %s", (img_time - mov_time).total_seconds()) return get_coords_from_geotag(geotagging)
def get_geotagging(exif): """ Bedre håndtering av geotag i exif-header Fra https://developer.here.com/blog/getting-started-with-geocoding-exif-image-metadata-in-python3 """ if not exif: raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def get_geotagging(fe): '''param: filename or exif object''' if isinstance(fe, str): exif = get_exif(fe) else: exif = fe if not exif: raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: # raise ValueError("No EXIF geotagging found") return geotagging for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] return geotagging
def get_geotagging(exif): if not exif: print("No EXIF metadata found") return geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: print("No EXIF geotagging found") return for (key, val) in GPSTAGS.items(): if key in exif[idx]: # if isinstance(exif[idx][key],bytes): # x = exif[idx][key].decode("utf-8") # geotagging[val] = x #else: geotagging[val] = exif[idx][key] return geotagging
def get_geotagging(image_name): image = Image.open(image_name) image.verify() exif = image._getexif() #if not exif: #raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] #jsonstring = json.dumps(geotagging) #return jsonstring return geotagging
def get_geotags(file_path): image = Image.open(file_path) image.verify() exif = image._getexif() if not exif: print() raise Exception(f"No EXIF metadata found for file {file_path}") geotags = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: print() raise Exception(f"No EXIF geotags found for file {file_path}") for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotags[val] = exif[idx][key] return geotags
def get_geotagging(imagename): exif = Image.open(imagename) exif.verify() exifdata = exif.getexif() #return exif if not exifdata: raise ValueError("No EXIF metadata found") geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exifdata: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exifdata[idx]: geotagging[val] = exifdata[idx][key] jsonstring = json.dumps(geotagging) return jsonstring
def get_labeled_exif(img: Union[Image, str]) -> dict: """ References ---------- [1] https://www.exiv2.org/tags.html [2] http://www.cipa.jp/std/documents/e/DC-008-2012_E.pdf [3] https://www.exif.org/ [4] https://en.wikipedia.org/wiki/Exif """ if isinstance(img, str): pil_img = PIL.Image.open(img) # elif isinstance(img, Image): else: pil_img = img try: exif = pil_img._getexif() or {} except: try: exif = dict(pil_img.getexif()) or {} except: raise ValueError("Invalid input image") labeled = {} for (key, val) in exif.items(): labeled[TAGS.get(key)] = val geotagging = {} if labeled.get("GPSInfo"): for (key, val) in GPSTAGS.items(): if key in labeled["GPSInfo"]: geotagging[val] = labeled["GPSInfo"][key] labeled["GPSInfo"] = geotagging return labeled
exifd = im._getexif() #keys = list(exifd.keys()) # wszystkie kody tagów obecnych w obrazku ImageLength = exifd[TAGSr['ImageLength']] ImageWidth = exifd[TAGSr['ImageWidth']] Make = exifd[TAGSr['Make']] Model = exifd[TAGSr['Model']] DateTimeOriginal = exifd[TAGSr['DateTimeOriginal']] print(DateTimeOriginal) fp.close() #%% wypisanie wszystkich wartoći tagów przykładowego obrazka for ek, ev in exifd.items(): if ek != TAGSr['MakerNote']: print(ek, TAGS.get(ek, ek), ev) #%% wypisanie jak rozwijają się kody tagów i gpstagów na ich nazwy for k, v in GPSTAGS.items(): print(k, v) #print(k if k==51041 else "",end='') for k, v in TAGS.items(): print(k, v) #%% import os, hashlib #ptht = r'\\KABATY\Users\Public\Pictures\card_dcim_camera' ptht = r'c:\Users\Public\Pictures\card_dcim_camera' ld = os.listdir(ptht) lj = [ld[i] for i in range(len(ld)) if ld[i].endswith('.jpg')] # lista jpeg-ów lm = [ld[i] for i in range(len(ld)) if not ld[i].endswith('.jpg')] # ~lista mpeg=ów print(len(ld), len(lj), len(lm))
def get_picture_data(self, fname, geolocator): _TAGS_r = dict(((v, k) for k, v in TAGS.items())) _GPSTAGS_r = dict(((v, k) for k, v in GPSTAGS.items())) date = 'Unknown' location = 'Unknown' orientation = '' th_name = '' rz_name = '' width = 0 height = 0 make = '' model = '' try: img = Image.open(fname) width, height = img.size except Exception as e: print('get_picture_data Exception e: ', e, ' fname: ', fname) width = -1 height = -1 return date, location, orientation, rz_name, th_name, width, height, make, model exifd = img._getexif() # as dict try: keys = list(exifd.keys()) except: return date, 'geo-nokeys', orientation, rz_name, th_name, width, height, make, model keys = [k for k in keys if k in TAGS] if (37510) in keys: keys.remove(_TAGS_r["UserComment"]) if (37500) in keys: keys.remove(_TAGS_r["MakerNote"]) try: img.close() except Exception as e: print('close Exception e: ', e, ' fname: ', fname) # symbolic name of keys for k in keys: val = exifd[k] res = type(val) if res == str: try: val = val.decode('utf-8') except: val = exifd[k] if (TAGS[k] == 'DateTime'): date = val if (TAGS[k] == 'Orientation'): orientation = self.get_orientation_tag(val) # 271 == Make if (TAGS[k] == 'Make'): make = val # 272 == Model if (TAGS[k] == 'Model'): model = val if (34853) not in keys: location = '34853 not in keys' return date, location, orientation, rz_name, th_name, width, height, make, model gpsinfo = exifd[_TAGS_r["GPSInfo"]] lat, lon = self.get_lat_lon(exifd) if lat == None or lon == None: location = lat else: coord = (lat, lon) try: location = geolocator.reverse(coord) if location == 'Unknown': print('location: ', fname, ' ', location, coord) except Exception as e: location = 'Service timed out' return date, location, orientation, rz_name, th_name, width, height, make, model
# coding: utf-8 from PIL.ExifTags import TAGS, GPSTAGS RTAGS = {v: k for (k, v) in TAGS.items()} RGPSTAGS = {v: k for (k, v) in GPSTAGS.items()} GPSINFO = RTAGS["GPSInfo"] def coord_to_deg(values): # every coordinate is a list of 3 pairs # every pair is a fraction ( (n, d) -> n/d ) # the 3 values are °, ' and " (degree, minute and second) deg = 0 for i in range(3): (n, d) = values[i] if d != 0: deg += n/(d * (60.**i)) return deg def extract_location(image): if not hasattr(image, "_getexif"): return {} exif = image._getexif() if not exif: return {} try: gpsinfo = exif[GPSINFO] lat = coord_to_deg(gpsinfo[RGPSTAGS["GPSLatitude"]]) if gpsinfo[RGPSTAGS["GPSLatitudeRef"]] == "S": lat = -lat lng = coord_to_deg(gpsinfo[RGPSTAGS["GPSLongitude"]])