Exemplo n.º 1
0
def get_exif_data(user_input):

    exif = Image.open(
        user_input)._getexif()  # Opening file and get exif information

    # Error handling if exif data exists
    if exif is not None:
        for key, value in exif.items():
            name = TAGS.get(key, key)
            exif[name] = exif.pop(key)
    else:
        return print("No GPS/Location Data Exists!")

    # Iphone
    if 'GPSInfo' in exif:  #Exif/GPS data is lost when an image is uploaded to Slack, we NEED RAW data.
        for key in exif['GPSInfo'].keys():
            name = GPSTAGS.get(key, key)  #GPSTAGS from PIL
            exif['GPSInfo'][name] = exif['GPSInfo'].pop(key)
        exif_df = pd.DataFrame.from_dict(
            exif['GPSInfo'],
            orient='index')  # Save to DataFrame from Dictionary
        exif_df = exif_df.T[new_columns]
        exif_datetime = pd.DataFrame.from_dict(
            exif, orient='index'
        )  # Isolate DateTimeOriginal from original exif dictionary
        exif_df['DateTimeOriginal'] = exif_datetime.T[
            'DateTimeOriginal']  # Add new column to exif_df with DateTimeOriginal
        exif_df["PhotoName"] = user_input[7:]
        exif_df  # Important?
        disasters.append(
            exif_df)  # Adding exif_df to Disasters scaffolding DataFrame
        return exif_df.to_csv('disasters.csv',
                              mode='a',
                              header=False,
                              index=False)  # Save to disasters.csv

    # Android
    if 34853 in exif:  #Exif data from Android phones
        for key in exif[34853].keys():
            name = GPSTAGS.get(key, key)
            exif[34853][name] = exif[34853].pop(key)

        exif_df_android = pd.DataFrame.from_dict(exif[34853], orient='index')
        exif_df_android = exif_df_android.T[new_columns]
        exif_df_android['DateTimeOriginal'] = exif['DateTimeOriginal']
        exif_df_android["PhotoName"] = user_input[7:]
        exif_df_android
        disasters.append(exif_df_android)
        return exif_df_android.to_csv('disasters.csv',
                                      mode='a',
                                      header=False,
                                      index=False)
Exemplo n.º 2
0
def get_gps(image):
	gps_latitude      = None
	gps_latitude_ref  = None
	gps_longitude     = None
	gps_longitude_ref = None
	exif_info = image._getexif()                            # Extract exifs from photo
	if exif_info:
		for tag, value in exif_info.items():        # Loop on exifs of photo
			decoded = TAGS.get(tag, tag)                    # Exif code
			if decoded == "GPSInfo":                            # Exif is GPSInfo
				for t in value:                                         # Loop on sub-exifs
					sub_decoded = GPSTAGS.get(t, t)     # Sub-exif code
					if   sub_decoded == 'GPSLatitude':
						gps_latitude = value[t]
					elif sub_decoded == 'GPSLatitudeRef':
						gps_latitude_ref = value[t]
					elif sub_decoded == 'GPSLongitude':
						gps_longitude = value[t]
					elif sub_decoded == 'GPSLongitudeRef':
						gps_longitude_ref = value[t]
						
				if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
					lat = convert_to_degrees(gps_latitude)
					lat_lon_txt = str(lat)+gps_latitude_ref
					if gps_latitude_ref != "N":
						lat = 0 - lat
					lon = convert_to_degrees(gps_longitude)
					lat_lon_txt = lat_lon_txt+' - '+str(lon)+gps_longitude_ref
					if gps_longitude_ref != "E":
						lon = 0 - lon
					return lat, lon, lat_lon_txt
	return False,False,None
Exemplo n.º 3
0
def get_exif_data(imgpath):
    """
    Get a dict of all of the metadata in the EXIF portion of an image.
    Returns a dictionary of the exif data. Also converts the GPS Tags.
    https://www.codingforentrepreneurs.com/blog/extract-gps-exif-images-python/
    Uses the PIL package.

    Input:
        imgpath - a file Path
    Returns:
        exif_data - a dict of the EXIF contents
    """
    exif_data = {}
    try:
        image = Image.open(imgpath)
    except:
        print("Failed to open ", imgpath)

    info = image._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps_data = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]

                exif_data[decoded] = gps_data
            else:
                exif_data[decoded] = value
    else:
        print("No GPS info in ", imgpath)
    image.close()
    return exif_data
Exemplo n.º 4
0
def get_gps_data(i):
    """
    Extract lat, lon, and altitude from a PIL image object
    This calls latlon_from_gps_data to decode the dict values
    Uses the PIL package.

    Input:
        i - image object returned by i=Image.open(imgpath)
    Returns:
        lat, lon, alt - floating point values in degrees, degrees, and meters
    """
    info = i._getexif()
    exif_data = {}
    lat = np.nan
    lon = np.nan
    alt = np.nan
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        if decoded == "GPSInfo":
            gps_data = {}
            for t in value:
                sub_decoded = GPSTAGS.get(t, t)
                gps_data[sub_decoded] = value[t]

            lat, lon, alt = latlon_from_gps_data(gps_data)

    return lat, lon, alt
Exemplo n.º 5
0
    def parse_data(self, path, filetype, **kwargs):
        self.filename = path

        if filetype not in FileTypes.IMAGES:
            return None

        self.image = Image.open(self.filename)

        if self.metadata:
            return self

        exif_data = {}
        info = self.image._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value

        self.metadata = exif_data
        self._parse_metadata()

        return self
Exemplo n.º 6
0
def extractCoordinates(exifValue):
    latRef = None
    longitRef = None
    lat = None
    longit = None

    #geocoding
    gpsData = {}
    for gpsTag in exifValue:
        tagElem = GPSTAGS.get(gpsTag, gpsTag)
        gpsData[tagElem] = exifValue[gpsTag]

    if "GPSLatitude" in gpsData:
        lat =  gpsData["GPSLatitude"]
        lat = decimalCoordinatesToDegress(lat)
    if "GPSLongitude" in gpsData:
        longit =  gpsData["GPSLongitude"]
        longit = decimalCoordinatesToDegress(longit)
    if "GPSLatitudeRef" in gpsData:
        latRef =  gpsData["GPSLatitudeRef"]
    if "GPSLongitudeRef" in gpsData:
        longitRef =  gpsData["GPSLongitudeRef"]

    if latRef is not None and latRef != "N":
        lat = 0 - lat
    if longitRef is not None and longitRef != "E":
        longit = 0 - longit

    return lat,longit
Exemplo n.º 7
0
def get_gps_details(img):
    """Function for extracting GPS data from image

    Args:
        img (.jpeg / .png et al.): an image file

    Returns:
        Dictionary with following key: value pairs:
            'GPSLatitudeRef': str = 'N' or 'S'
            'GPSLatitude': tuple of tuples,
            'GPSLongitudeRef': str = 'E' or 'W',
            'GPSLongitude': tuple of tuples,
            'GPSAltitudeRef': byte string,
            'GPSAltitude': tuple,
            'GPSTimeStamp': tuple of tuples,
            'GPSSpeedRef': str,
            'GPSSpeed': tuple,
            'GPSImgDirectionRef': str,
            'GPSImgDirection': tuple,
            'GPSDestBearingRef': str,
            'GPSDestBearing': tuple,
            'GPSDateStamp': str representing datetime,
            'GPSHPositioningError': tuple}
    """
    gpsinfo = {}
    exif = {TAGS[k]: v for k, v in img._getexif().items() if k in TAGS}
    for item in exif['GPSInfo'].keys():
        name = GPSTAGS.get(item, item)
        gpsinfo[name] = exif['GPSInfo'][item]
    return gpsinfo
Exemplo n.º 8
0
def get_exif_data(image):
	'''fucntion to return info about meta data of the image.
		special attention has been paid to GPSInfo which helps to get data about latitude, longitude and references.
	'''

	exif_data = {}
	meta_data = image._getexif()
    
	if meta_data:
		for key, value in meta_data.items():
	    	#print(key)
			decoded_key = TAGS.get(key, key)  #it is used to decode the key .
	    	#print(str(key) + " " + decoded_key + " " + str(value))
	    	#print(str(key) + " " + decoded_key) # prints the key and its decoded key.--> used for learning
			if decoded_key == "GPSInfo":
				gps_data = {} # a dictionary to store info about gps data of image
				for idx in value:
					#print(idx) #value ranges from 0 to 6.
					sub_decoded_key = GPSTAGS.get(idx, idx) # it is used to decode the key.
					#print(sub_decoded_key) # attributes like latilude, longitude , altitude and their references.
					gps_data[sub_decoded_key] = value[idx]

				exif_data[decoded_key] = gps_data
			else:
				exif_data[decoded_key] = value
    
	return exif_data
Exemplo n.º 9
0
    def build_gps_dict(self):
        raw_values = {}
        for tag, value in self.exif.items():
            if TAGS.get(tag, tag) == "GPSInfo":
                raw_values = value

        if not raw_values:
            raise self.Invalid("GPSInfo not found in exif")

        gps_dict = {
            GPSTAGS.get(tag, tag): raw_values[tag]
            for tag in raw_values
        }

        # validation

        missing_keys = [
            key for key in (
                "GPSLatitudeRef",
                "GPSLongitudeRef",
                "GPSLatitude",
                "GPSLongitude",
            ) if key not in gps_dict
        ]

        if missing_keys:
            raise self.Invalid(
                f"{','.join(missing_keys)} missing from GPS dict")

        return gps_dict
Exemplo n.º 10
0
def get_exif_data(image):
    '''
    EXIF data is stored data in an image file that includes the date the photo was taken, resolution, shutter speed, focal length, and other camera settings. 
    Getting the EXIF data for an image results in a dictionary indexed by EXIF numeric tags.
    '''
    info = image._getexif()
    # If there is no exif data then return None
    if (info is None):
        return info
    exif_data = {}
    # For the different tags and value we got from our exif data
    # Let's get GPSInfo and other required value which we will use
    for tag, value in info.items():
        # Getting the required data from the dictionary
        decoded = TAGS.get(tag, tag)
        # Pulling out the GPS specific tags
        if (decoded == "GPSInfo"):
            gps_data = {}
            for t in value:
                sub_decoded = GPSTAGS.get(t, t)
                gps_data[sub_decoded] = value[t]

            exif_data[decoded] = gps_data
        else:
            exif_data[decoded] = value
    return exif_data
Exemplo n.º 11
0
def PIL_exif_data_GPS(filename):
    if magic.from_file(filename, mime=True) == "image/jpeg":
        print("Extraction of GPS data from: %s" % (filename, ))
        image = Image.open(filename)
        exif_data = {}
        exif = image._getexif()
        latitude = None
        longitude = None
        if exif:
            for tag, value in exif.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]
                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        if "GPSInfo" in exif_data:
            gps_info = exif_data["GPSInfo"]
            gps_longitude = None
            gps_latitude = None
            if "GPSLatitude" in gps_info:
                gps_latitude = gps_info["GPSLatitude"]
            if "GPSLatitudeRef" in gps_info:
                gps_latitude_ref = gps_info["GPSLatitudeRef"]
            if "GPSLongitude" in gps_info:
                gps_longitude = gps_info["GPSLongitude"]
            if "GPSLongitudeRef" in gps_info:
                gps_longitude_ref = gps_info["GPSLongitudeRef"]
            if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
                latitude = helper.to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    latitude = 0 - latitude
                longitude = helper.to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    longitude = 0 - longitude

        helper.sqlite_insert("Parsed_GPS_Latitude", str(latitude),
                             os.path.basename(filename))
        helper.sqlite_insert("Parsed_GPS_Langitude", str(longitude),
                             os.path.basename(filename))

        try:
            if latitude != None and longitude != None:
                geolocator = Nominatim(user_agent="imago-forensics")
                ls = str(latitude) + "," + str(longitude)
                location = geolocator.reverse(ls)
                address = location.raw["address"]
                for a in address.keys():
                    helper.sqlite_insert(a, str(address[a]),
                                         os.path.basename(filename))
        except:
            print "Problem during geopy decode"

        return latitude, longitude
    else:
        print "GPS works only with JPEG"
    return None
Exemplo n.º 12
0
def ExtractGPSDictionary(fileName):

    try:
        pilImage = Image.open(fileName)
        exifData = pilImage._getexif()

    except Exception:
        # If exception occurs from PIL processing
        # Report the
        return None, None

    # Interate through the exifData
    # Searching for GPS Tags

    imageTimeStamp = "NA"
    cameraModel = "NA"
    cameraMake = "NA"
    gpsData = False

    gpsDictionary = {}

    if exifData:

        for tag, theValue in exifData.items():

            # obtain the tag
            tagValue = TAGS.get(tag, tag)

            # Collect basic image data if available

            if tagValue == 'DateTimeOriginal':
                imageTimeStamp = exifData.get(tag)

            if tagValue == "Make":
                cameraMake = exifData.get(tag)

            if tagValue == 'Model':
                cameraModel = exifData.get(tag)

            # check the tag for GPS
            if tagValue == "GPSInfo":

                gpsData = True

                # Found it !
                # Now create a Dictionary to hold the GPS Data

                # Loop through the GPS Information
                for curTag in theValue:
                    gpsTag = GPSTAGS.get(curTag, curTag)
                    gpsDictionary[gpsTag] = theValue[curTag]

                basicExifData = [imageTimeStamp, cameraMake, cameraModel]

                return gpsDictionary, basicExifData

        if gpsData == False:
            return None, None
    else:
        return None, None
Exemplo n.º 13
0
Arquivo: tests.py Projeto: lorty1/exif
    def test_picture_(self):
        image2 = Image.open("./test1.jpg")
        exif = image2._getexif()
        if exif is not None:
            for key, value in exif.items():
                name = TAGS.get(key, key)
                exif[name] = exif.pop(key)

                if 'GPSInfo' in exif:
                    for key in exif['GPSInfo'].keys():
                        name = GPSTAGS.get(key, key)
                        exif['GPSInfo'][name] = exif['GPSInfo'].pop(key)
            info = exif['GPSInfo']
            print(info)
            for key in ['Latitude', 'Longitude']:
                if 'GPS' + key in info and 'GPS' + key + 'Ref' in info:
                    e = info['GPS' + key]
                    ref = info['GPS' + key + 'Ref']
                    info[key] = (e[0][0] / e[0][1] + e[1][0] / e[1][1] / 60 +
                                 e[2][0] / e[2][1] / 3600) * (
                                     -1 if ref in ['S', 'W'] else 1)

            if 'Latitude' in info and 'Longitude' in info:
                coord = [info['Latitude'], info['Longitude']]
                print('coord', coord, type(coord), type(coord[0]),
                      type(coord[1]))
                return self.get_coordonate(coord)
Exemplo n.º 14
0
def get_exif_data(image):
    """Returns a dictionary from the exif data of a PIL Image item. Also converts the GPS Tags"""

    exif_data = {}
    print "BEFORE"
    info = image._getexif()
    # print image
    # info = image.tag.tags
    print "AFTER"
    if info:
        "IN INFO"
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            print tag
            if decoded == "GPSInfo":
                gps_data = {}

                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]

                exif_data[decoded] = gps_data

            else:
                exif_data[decoded] = value

    return exif_data
Exemplo n.º 15
0
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    logger = logging.getLogger(__name__)

    if PIL.PILLOW_VERSION == '3.0.0':
        warnings.warn('Pillow 3.0.0 is broken with EXIF data, consider using '
                      'another version if you want to use EXIF data.')

    img = PILImage.open(filename)
    try:
        exif = img._getexif() or {}
    except ZeroDivisionError:
        logger.warning('Failed to read EXIF data.')
        return None

    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if 'GPSInfo' in data:
        try:
            data['GPSInfo'] = {GPSTAGS.get(tag, tag): value
                               for tag, value in data['GPSInfo'].items()}
        except AttributeError:
            logger = logging.getLogger(__name__)
            logger.info('Failed to get GPS Info')
            del data['GPSInfo']
    return data
Exemplo n.º 16
0
def get_exif_data(image):
    """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
    exif_data = {}

    try:
        info = image._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)

                ### GPS
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data

                ### Picture Taken Time
                if decoded == 'DateTime':
                    exif_data[decoded] = value
    except Exception:
        print("There is no EXIF INFO")

    return exif_data
Exemplo n.º 17
0
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    logger = logging.getLogger(__name__)

    img = _read_image(filename)

    try:
        exif = img._getexif() or {}
    except ZeroDivisionError:
        logger.warning('Failed to read EXIF data.')
        return None

    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if 'GPSInfo' in data:
        try:
            data['GPSInfo'] = {
                GPSTAGS.get(tag, tag): value
                for tag, value in data['GPSInfo'].items()
            }
        except AttributeError:
            logger = logging.getLogger(__name__)
            logger.info('Failed to get GPS Info')
            del data['GPSInfo']
    return data
Exemplo n.º 18
0
 def get_gps_info(self, tag=34853):
     temp = self.get_by_tag_num(tag)
     GPSDict = {}
     for key in temp.keys():
         GPStag = GPSTAGS.get(key, key)
         GPSDict[GPStag] = self.exif_data[tag][key]
     return GPSDict
Exemplo n.º 19
0
	def getGeoposition(self):
		def _convert_to_degress(value):
			d = float(value[0][0])/float(value[0][1])
			m = float(value[1][0])/float(value[1][1])
			s = float(value[2][0])/float(value[2][1])
			return d + (m / 60.0) + (s / 3600.0)
		gp = self.extinfo.get('GPSInfo',None)
		if gp is None:
			return None,None
		gpsinfo = {}
		for k in gp.keys():
			decoded = GPSTAGS.get(k,k)
			gpsinfo[decoded] = gp[k]
		lat = None
		lon = None
		gps_latitude =gpsinfo.get('GPSLatitude')
		gps_latitude_ref = gpsinfo.get('GPSLatitudeRef')
		gps_longitude = gpsinfo.get('GPSLongitude')
		gps_longitude_ref = gpsinfo.get('GPSLongitudeRef')
		if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
			lat = _convert_to_degress(gps_latitude)
			if gps_latitude_ref != 'N':
				lat = 0 - lat
			lon = _convert_to_degress(gps_longitude)
			if gps_longitude_ref != 'E':
				lon = 0 - lon
		return lat, lon
Exemplo n.º 20
0
def readExif(exif):

    
    data = {}
    exif_data = {}
    gps_data = {}
 
    if exif is None:
        return data
    
    for k,v in exif.items():
       if k in tag_name_to_id:
           data[tag_name_to_id[k]] = v
       decoded = TAGS.get(k, k)
       if decoded == "GPSInfo":
           for t in v:
               sub_decoded = GPSTAGS.get(t, t)
               gps_data[sub_decoded] = v[t]

           exif_data[decoded] = gps_data
       else:
           exif_data[decoded] = v
       
       #else:
       #   data[k] = v
 
    data['GPSInfo'] = gps_data
 
    # These fields are in UCS2/UTF-16, convert to something usable within python
    for k in ['XPTitle', 'XPComment', 'XPAuthor', 'XPKeywords', 'XPSubject']:
        if k in data:
            data[k] = data[k].decode('utf-16').rstrip('\x00')

    print data
    return data
Exemplo n.º 21
0
def get_exif(filename):
    """Extrait les informations numériques EXIF d'une image. Les données brutes
    sont aussi décryptée.

    Parameters
    ----------
    filename : str
        Nom du fichier à partir duquel charger l'image.

    Returns
    -------
    exif : dict
        Données EXIF partiellement décryptées.
    """

    # Ouverture du fichier image
    exif = Image.open(filename)._getexif()

    if exif is not None:
        for key, value in copy.deepcopy(exif).items():
            name = TAGS.get(key, key)
            exif[name] = exif.pop(key)

        if 'GPSInfo' in exif:
            for key in copy.deepcopy(exif['GPSInfo']).keys():
                name = GPSTAGS.get(key, key)
                exif['GPSInfo'][name] = exif['GPSInfo'].pop(key)
        else:
            print("Pas d'information de géolocalisation dans cette image.")

    return exif
Exemplo n.º 22
0
def show_geodata_for_image(imageSrc, imageFilePath):
    """
	Searches for GPS data in the image and shows it if found and valid.
	"""
    exitData = {}
    try:
        imageFile = Image.open(imageFilePath)
        info = imageFile._getexif()
    except:
        return

    if info:
        for (tag, value) in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == 'GPSInfo':
                gpsData = {}
                for t in value:
                    decodedGps = GPSTAGS.get(t, t)
                    gpsData[decodedGps] = value[t]

                if 'GPSLatitude' in gpsData and 'GPSLatitudeRef' in gpsData and 'GPSLongitude' in gpsData and 'GPSLongitudeRef' in gpsData:
                    latitude = convert_to_degrees(gpsData['GPSLatitude'])
                    if gpsData['GPSLatitudeRef'] != 'N':
                        latitude = 0 - latitude
                    longitude = convert_to_degrees(gpsData['GPSLongitude'])
                    if gpsData['GPSLongitude'] != 'E':
                        longitude = 0 - longitude
                    if latitude != 0 and longitude != 0:
                        print 'GPS data for %s: latitude=%f%s, longitude=%f%s' % (
                            imageSrc, latitude, gpsData['GPSLatitudeRef'],
                            longitude, gpsData['GPSLongitudeRef'])

                break
Exemplo n.º 23
0
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    logger = logging.getLogger(__name__)

    img = _read_image(filename)

    try:
        with warnings.catch_warnings(record=True) as caught_warnings:
            exif = img._getexif() or {}
    except ZeroDivisionError:
        logger.warning('Failed to read EXIF data.')
        return None

    for w in caught_warnings:
        fname = (filename.filename
                 if isinstance(filename, PILImage.Image) else filename)
        logger.warning(f'PILImage reported a warning for file {fname}\n'
                       f'{w.category}: {w.message}')

    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if 'GPSInfo' in data:
        try:
            data['GPSInfo'] = {
                GPSTAGS.get(tag, tag): value
                for tag, value in data['GPSInfo'].items()
            }
        except AttributeError:
            logger.info('Failed to get GPS Info')
            del data['GPSInfo']
    return data
Exemplo n.º 24
0
def get_gps(exif_info):
    gps = {}
    # EXIF情報 に GPSInfo タグが含まれているときに処理
    if 'GPSInfo' in exif_info:
    # EXIF情報から GPS情報を取り出す
        gps_tags = exif_info['GPSInfo']
    # GPS情報を辞書に格納する
        for t in gps_tags:
            gps[GPSTAGS.get(t,t)] = gps_tags[t]

        # 緯度/経度のタグがあることを確認した上で処理する
        is_lati = gps['GPSLatitude'] 
        is_lati_ref = gps['GPSLatitudeRef']
        is_longi = gps['GPSLongitude']
        is_longi_ref = gps['GPSLongitudeRef']
        
        if is_lati and is_lati_ref and is_longi and is_longi_ref:
            # 緯度/経度ダグを度分秒(DMS)形式に変換する
            lati = format_DMS(is_lati_ref, is_lati)
            longi = format_DMS(is_longi_ref, is_longi)
            return f'{lati} {longi}'
        else:
            return print('このファイルには緯度/経度の情報がありません。')
    else:
        return print('このファイルにはGPS情報がありません。')
Exemplo n.º 25
0
    def pull_exif(self, location):
        """Pull exif data from an image.
        
        Args:
            location (str):
                Filepath to the image.
                
        Returns:
            Exif data of the image.
        """

        image = Image.open(location)

        exif_data = dict()
        info = image._getexif()
        if info:
            for key, value in info.items():
                name = TAGS.get(key, key)
                if name == 'GPSInfo':
                    gps = dict()
                    for subvalue in value:
                        nested = GPSTAGS.get(subvalue, subvalue)
                        gps[nested] = value[subvalue]
                    exif_data[name] = gps
                else:
                    exif_data[name] = value
        return exif_data
Exemplo n.º 26
0
def getLocationAsDict(pfnImage):

    img = Image.open(pfnImage)

    exif = img._getexif() or {}

    gps_tag_dec = 34853

    gps_dict = exif.get(gps_tag_dec, None)

    gpsinfo = {}

    if gps_dict is not None:

        for key in gps_dict.keys():
            decode = GPSTAGS.get(key, key)
            gps_value = gps_dict.get(key, None)

            if decode == 'GPSTimeStamp':
                gps_value = _gps_process_time_tuple(gps_value)

            if isinstance(gps_value, tuple):
                gps_value = _gps_tuple_processing(gps_value)

            if isinstance(gps_value, bytes):
                gps_value = gps_value.decode('utf-8')

            #print("tag: {}  value: {}  type of value: {}".format(
            #    decode, gps_value, type(gps_value)))

            gpsinfo[decode] = gps_value

    gpsinfo['error'] = 'Location Exif header not found in image'

    return gpsinfo
Exemplo n.º 27
0
def ExtractGPSDictionary(fileName):
     
    try:
        pilImage = Image.open(fileName)
        exifData = pilImage._getexif()
    
    except Exception:
        # If exception occurs from PIL processing
        # Report the 
        return None, None
    
    # Interate through the exifData
    # Searching for GPS Tags
    
    imageTimeStamp = "NA"
    cameraModel = "NA"
    cameraMake = "NA"
    gpsData = False
    
    gpsDictionary = {}
    
    if exifData:
            
        for tag, theValue in exifData.items():
                
            # obtain the tag
            tagValue = TAGS.get(tag, tag)
                
            # Collect basic image data if available
            
            if tagValue == 'DateTimeOriginal':
                imageTimeStamp = exifData.get(tag)
                
            if tagValue == "Make":
                cameraMake = exifData.get(tag)
                
            if tagValue == 'Model':
                cameraModel = exifData.get(tag)
                
            # check the tag for GPS
            if tagValue == "GPSInfo":
                
                gpsData = True;
                
                # Found it !
                # Now create a Dictionary to hold the GPS Data
                
                # Loop through the GPS Information
                for curTag in theValue:
                    gpsTag = GPSTAGS.get(curTag, curTag)
                    gpsDictionary[gpsTag] = theValue[curTag]
                
                basicExifData = [imageTimeStamp, cameraMake, cameraModel]    
                
                return gpsDictionary, basicExifData
            
        if gpsData == False:
            return None, None
    else:
        return None, None
Exemplo n.º 28
0
    def get_exif_data(image):
        """Returns a dictionary from the exif data of an PIL Image
        item. Also converts the GPS Tags"""
        exif_data = {}
        try:
            info = image._getexif()

        except OverflowError as e:
            if e.message == "cannot fit 'long' into an index-sized integer":
                # Error in PIL when exif data is corrupt.
                return None
            else:
                raise e
        # except struct.error as e:
        #     if e.message == "unpack requires a string argument of length 2":
        #         # Error in PIL when exif data is corrupt.
        #         return None
        #     else:
        #         raise e
        if info:
            for tag, value in list(info.items()):
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]
                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        return exif_data
Exemplo n.º 29
0
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    logger = logging.getLogger(__name__)

    if PIL.PILLOW_VERSION == '3.0.0':
        warnings.warn('Pillow 3.0.0 is broken with EXIF data, consider using '
                      'another version if you want to use EXIF data.')

    img = _read_image(filename)

    try:
        exif = img._getexif() or {}
    except ZeroDivisionError:
        logger.warning('Failed to read EXIF data.')
        return None

    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if 'GPSInfo' in data:
        try:
            data['GPSInfo'] = {
                GPSTAGS.get(tag, tag): value
                for tag, value in data['GPSInfo'].items()
            }
        except AttributeError:
            logger = logging.getLogger(__name__)
            logger.info('Failed to get GPS Info')
            del data['GPSInfo']
    return data
Exemplo n.º 30
0
    def extract(self, filepath):
        fd = Image.open(filepath)
        exif = fd._getexif() # raw exif
        gps = {} # raw undecoded gps
        results = {} 

        if exif:
            for (k, v) in exif.items():
                results[TAGS.get(k, k)] = v

        if exif and ExifExtract.GPSINFO in exif:
            for t in exif[ExifExtract.GPSINFO]:
                sub_decoded = GPSTAGS.get(t, t)
                gps[sub_decoded] = exif[ExifExtract.GPSINFO][t]

        if 'GPSLatitude' in gps and 'GPSLatitudeRef' in gps and 'GPSLongitude' in gps and 'GPSLongitudeRef' in gps:
            lat_deg = self._to_degrees(gps['GPSLatitude'])
            if 'N' is not gps['GPSLatitudeRef']:
                lat_deg *= -1

            lng_deg = self._to_degrees(gps['GPSLongitude'])
            if 'E' is not gps['GPSLongitudeRef']:
                lng_deg *= -1

            results['GPS'] = {
                'longitude': lng_deg,
                'latitude': lat_deg
            }

        return results
Exemplo n.º 31
0
    def _get_exif_data(self, image):
        """Returns a dictionary from the exif data of an PIL Image item.
        Also converts the GPS Tags"""

        exif_data = {}
        try:
            info = image._getexif()
        except AttributeError:
            return exif_data
        except IndexError:
            return exif_data
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value

        return exif_data
Exemplo n.º 32
0
def get_exif_data(image):
    """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
    info = image._getexif()
    if not info:
        return {}
    exif_data = {TAGS.get(tag, tag): value for tag, value in info.items()}

    def is_fraction(val):
        return isinstance(val, tuple) and len(val) == 2 and isinstance(
            val[0], int) and isinstance(val[1], int)

    def frac_to_dec(frac):
        return float(frac[0]) / float(frac[1])

    if "GPSInfo" in exif_data:
        gpsinfo = {
            GPSTAGS.get(t, t): v
            for t, v in exif_data["GPSInfo"].items()
        }
        for tag, value in gpsinfo.items():
            if is_fraction(value):
                gpsinfo[tag] = frac_to_dec(value)
            elif all(is_fraction(x) for x in value):
                gpsinfo[tag] = tuple(map(frac_to_dec, value))
        exif_data["GPSInfo"] = gpsinfo
    return exif_data
Exemplo n.º 33
0
def get_exif(fn):
    exif_dict = {}
    img = Image.open(fn)
    info = img._getexif()
    #iterate through all exif data
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        #format geo data
        if decoded == "GPSInfo":
            gps_data = {}
            for t in value:
                sub_decoded = GPSTAGS.get(t, t)
                gps_data[sub_decoded] = value[t]
            exif_dict["Latitude"] = convert_2_degrees(gps_data["GPSLatitude"])
            exif_dict["Longitude"] = convert_2_degrees(
                gps_data["GPSLongitude"])
        #format datetime data
        elif decoded == "DateTimeOriginal":
            exif_dict["Datetime"] = datetime.datetime.strptime(
                value, "%Y:%m:%d %H:%M:%S")
            exif_dict["Date_String"] = exif_dict["Datetime"].strftime(
                "%d. %b. %y")
            exif_dict["Time_String"] = exif_dict["Datetime"].strftime("%H:%M")
#        else:
#            exif_dict[decoded]=value
    return exif_dict
Exemplo n.º 34
0
def get_lat_lng(filename):
    data = {}
    im = Image.open(filename)
    info = im._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps[sub_decoded] = value[t]

                data[decoded] = gps
            else:
                data[decoded] = value
    lat = None
    lng = None
    if "GPSInfo" in data:
        gps = data["GPSInfo"]
        gps_lat = get_if_exist(gps, "GPSLatitude")
        gps_lat_r = get_if_exist(gps, "GPSLatitudeRef")
        gps_lng = get_if_exist(gps, "GPSLongitude")
        gps_lng_r = get_if_exist(gps, "GPSLongitudeRef")

        if gps_lat and gps_lng_r and gps_lng and gps_lng_r:
            lat = convert_deg(gps_lat)
            if gps_lat_r != "N":
                lat = 0 - lat
            lng = convert_deg(gps_lng)
            if gps_lng_r != "E":
                lng = 0 - lng

    return lat, lng
Exemplo n.º 35
0
def ExtractGPSDictionary(fileName):
    #open the image file using PIL
    try:
        pilImage = Image.open(fileName)
        EXIFData = pilImage._getexif()
    except:
        return None, None

    # set default values for some image attributes
    imageTimeStamp = "NA"
    cameraModel = "NA"
    cameraMake = "NA"

    if EXIFData:  # this will be a true statement as long as EXIFData does not return 'None"
        gpsDictionary = {}  # the dictionary we'll construct
        # iterate through the exif dictionary.
        for tag, value in EXIFData.items():
            # look up the English name for the tag in TAGS.
            tagName = TAGS.get(tag, tag)
            if tagName == 'DateTimeOriginal':
                imageTimeStamp = value
            if tagName == 'Make':
                cameraMake = value
            if tagName == 'Model':
                cameraModel = value
            if tagName == 'GPSInfo':  # found the GPS dictionary
                for gpsTag in value:
                    gpsTagName = GPSTAGS.get(gpsTag, gpsTag)
                    gpsDictionary[gpsTagName] = value[gpsTag]
        # the book returns here..
        basicEXIFData = [imageTimeStamp, cameraMake, cameraModel]
        return gpsDictionary, basicEXIFData
    else:
        return None, None,
Exemplo n.º 36
0
def _extract_gpsinfo(values):
    lat = None
    lon = None
    altitude = None
    gps_data = {}
    for t in values:
        sub_decoded = GPSTAGS.get(t, t)
        gps_data[sub_decoded] = values[t]

    gps_lat = _get_if_exist(gps_data, "GPSLatitude")
    gps_lat_ref = _get_if_exist(gps_data, 'GPSLatitudeRef')
    gps_lon = _get_if_exist(gps_data, 'GPSLongitude')
    gps_lon_ref = _get_if_exist(gps_data, 'GPSLongitudeRef')

    if gps_lat and gps_lat_ref and gps_lon and gps_lon_ref:
        lat = _convert_to_degress(gps_lat)
        if gps_lat_ref != "N":
            lat = 0 - lat

        lon = _convert_to_degress(gps_lon)
        if gps_lon_ref != "E":
            lon = 0 - lon

    altitude = _get_if_exist(gps_data, 'GPSAltitude')
    if altitude:
        altitude = _frac_to_float(altitude)
    return (lat, lon, altitude, gps_data)
Exemplo n.º 37
0
def get_exif_header(image):
   """Returns a dictionary from the exif header of an PIL Image. Also converts the GPS Tags.

   Args:
      image: 
   """
   try:
      info = image._getexif()
   except:
      raise gserror.EmptyExifHeaderError('could not found the exif header')
   
   if not info:
      raise gserror.EmptyExifHeaderError('empty exif header')
   
   exif_header = {}   
   for tag, value in info.items():
      tag_id = TAGS.get(tag, tag)
      if tag_id == __EXIF_GPS_INFO:
         gps_info = {}
         for t in value:
            gps_tag_id = GPSTAGS.get(t, t)
            gps_info[gps_tag_id] = value[t]
         exif_header[tag_id] = gps_info
      else:
         exif_header[tag_id] = value
   return exif_header
Exemplo n.º 38
0
def get_exif_data(image):
    """Return a dict from the exif data of a PIL Image and convert the GPS
    tags.
    """

    exif_data = {}
    info = image._getexif()

    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)

            if decoded == "GPSInfo":
                gps_data = {}

                for gps_tag in value:
                    sub_decoded = GPSTAGS.get(gps_tag, gps_tag)
                    gps_data[sub_decoded] = value[gps_tag]

                exif_data[decoded] = gps_data

            else:
                exif_data[decoded] = value

    return exif_data
def show_geodata_for_image(imageSrc, imageFilePath):
	"""
	Searches for GPS data in the image and shows it if found and valid.
	"""
	exitData = {}
	try:
		imageFile = Image.open(imageFilePath)
		info = imageFile._getexif()
	except:
		return

	if info:
		for (tag, value) in info.items():
			decoded = TAGS.get(tag, tag)
			if decoded == 'GPSInfo':
				gpsData = {}
				for t in value:
					decodedGps = GPSTAGS.get(t, t)
					gpsData[decodedGps] = value[t]

				if 'GPSLatitude' in gpsData and 'GPSLatitudeRef' in gpsData and 'GPSLongitude' in gpsData and 'GPSLongitudeRef' in gpsData:
					latitude = convert_to_degrees(gpsData['GPSLatitude'])
					if gpsData['GPSLatitudeRef'] != 'N':
						latitude = 0 - latitude
					longitude = convert_to_degrees(gpsData['GPSLongitude'])
					if gpsData['GPSLongitude'] != 'E':
						longitude = 0 - longitude
					if latitude !=0 and longitude != 0:
						print 'GPS data for %s: latitude=%f%s, longitude=%f%s' % (imageSrc, latitude, gpsData['GPSLatitudeRef'], longitude, gpsData['GPSLongitudeRef'])

				break
Exemplo n.º 40
0
def get_exif_info():
    img_file = 'osaka.jpg'
    img = Image.open(img_file)

    # _getexif 메소드를 사용해서, 이미지 속성을 담고 있는 사전 객체를 반환 받습니다.
    # 반환 값이 None 이면, 이 사진은 EXIF 정보를 가지고 있지 않은 것입니다.
    exif = img._getexif()
    if exif is None:
        print('There are no exif information in the photo.')
        return

    exif_data = {}
    for tag_id, tag_value in exif.items():
        # TAGS 사전에서 tag_id 로 값을 조회하고, 값이 없는 경우 tag_id 를 반환합니다.
        tag = TAGS.get(tag_id, tag_id)

        # tag 의 정보가 GPSInfo 라면, GPSTAGS 사전에서 다시 정보를 검색합니다.
        if tag == 'GPSInfo':
            gps_data = {}
            for gps_id in tag_value:
                gps_tag = GPSTAGS.get(gps_id, gps_id)
                gps_data[gps_tag] = tag_value[gps_id]

            exif_data[tag] = gps_data
        else:
            exif_data[tag] = tag_value

    return exif_data
Exemplo n.º 41
0
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    img = PILImage.open(filename)
    exif = img._getexif() or {}
    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if "GPSInfo" in data:
        data["GPSInfo"] = {GPSTAGS.get(tag, tag): value for tag, value in data["GPSInfo"].items()}
    return data
Exemplo n.º 42
0
def get_gps(f):
    gps_data = {}
    i = Image.open(f)
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        if decoded == "GPSInfo":
            for t in value:
                sub_decoded = GPSTAGS.get(t, t)
                gps_data[sub_decoded] = value[t]
    return gps_data
Exemplo n.º 43
0
def get_gps_lat_long_compass(path_image):
    image = Image.open(path_image)
    try:
        info = image._getexif()
    except Exception as e:
        print(e)
    if info:
        exif_data = {}
        for tag, value in list(info.items()):
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps_data = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]
                exif_data[decoded] = gps_data
            else:
                exif_data[decoded] = value
        exif_data_gpsInfo = exif_data.get('GPSInfo')
        if not exif_data_gpsInfo:
            raise ValueError("No GPS metadata found.")
        try:
            lat = exif_data_gpsInfo['GPSLatitude']
        except Exception as ex:
            erro = 1
        try:
            long = exif_data_gpsInfo['GPSLongitude']
        except Exception as ex:
            erro = 1

        try:
            if lat and int:
                lat = round(float(lat[0][0]) / float(lat[0][1]) + float(lat[1][0]) / float(lat[1][1]) / 60.0 + float(
                    lat[2][0]) / float(lat[2][1]) / 3600.0, 4)
                long = round(
                    float(long[0][0]) / float(long[0][1]) + float(long[1][0]) / float(long[1][1]) / 60.0 + float(
                        long[2][0]) / float(long[2][1]) / 3600.0, 4)
            if exif_data_gpsInfo['GPSLatitudeRef'] == 'S':
                lat = 0 - lat
            if exif_data_gpsInfo['GPSLongitudeRef'] == 'W':
                long = 0 - long
        except Exception as ex:
            erro = 1
        try:
            compas = exif_data_gpsInfo['GPSImgDirection']
            compas = compas[0] / compas[1]
        except Exception:
            try:
                compas = exif_data_gpsInfo['GPSTrack']
                compas = compas[0] / compas[1]
            except Exception:
                compas = -1
        return lat, long, compas
Exemplo n.º 44
0
def interpretGPS(gpsTag):
	
	gpsInfo = dict()
	try:
		for key in gpsTag.keys():
			decoded = GPSTAGS.get(key,key)
			gpsInfo[decoded] = gpsTag[key]
		
		return gpsInfo
	
	except:
		return None
Exemplo n.º 45
0
 def decode_gps(self, gps_field):
     gpsinfo = dict((GPSTAGS.get(k, k), v) for k, v in gps_field.iteritems())
     for field in ('GPSLatitudeRef', 'GPSLatitude', 'GPSLatitudeRef', 'GPSLongitude'):
         assert field in gpsinfo, 'failed to find field %s: %r' % (field, gpsinfo)
     assert gpsinfo['GPSLatitudeRef'] in 'NS'
     assert gpsinfo['GPSLongitudeRef'] in 'EW'
     lat = self.decode_gps_ref(gpsinfo['GPSLatitude'])
     if gpsinfo['GPSLatitudeRef'] == 'S':
         lat *= -1
     lng = self.decode_gps_ref(gpsinfo['GPSLongitude'])
     if gpsinfo['GPSLongitudeRef'] == 'W':
         lng *= -1
     return lat, lng, geohash.encode(lat, lng, precision=db.GEOHASH_PRECISION)
Exemplo n.º 46
0
Arquivo: image.py Projeto: praus/sigal
def _get_exif_data(filename):
    img = PILImage.open(filename)
    exif = img._getexif() or {}
    data = dict((TAGS.get(t, t), v) for (t, v) in exif.items())

    if 'GPSInfo' in data:
        gps_data = {}

        for tag in data['GPSInfo']:
            gps_data[GPSTAGS.get(tag, tag)] = data['GPSInfo'][tag]

        data['GPSInfo'] = gps_data

    return data
Exemplo n.º 47
0
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    img = PILImage.open(filename)
    exif = img._getexif() or {}
    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if "GPSInfo" in data:
        try:
            data["GPSInfo"] = {GPSTAGS.get(tag, tag): value for tag, value in data["GPSInfo"].items()}
        except AttributeError:
            logger = logging.getLogger(__name__)
            logger.info("Failed to get GPS Info", exc_info=True)
            del data["GPSInfo"]
    return data
Exemplo n.º 48
0
def get_exif_data(image):
    exif_data = {}
    info = image._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps_data = {}
                for gps_tag in value:
                    sub_decoded = GPSTAGS.get(gps_tag, gps_tag)
                    gps_data[sub_decoded] = value[gps_tag]
                exif_data[decoded] = gps_data
            else:
                exif_data[decoded] = value
    return exif_data
Exemplo n.º 49
0
	def getGpsData(self, gpsValue = None):
		
		if (gpsValue == None):
			gpsTag = self.searchExifKey(34853)
			if (gpsTag != None):
				gpsValue = gpsTag[2]
		
		if (gpsValue != None):
			gps_data = {}
			for t in gpsValue:
				sub_decoded = GPSTAGS.get(t, t)
				gps_data[sub_decoded] = gpsValue[t]
			return gps_data
		else:
			self.log.debug("Did not find GPS data in EXIF data.")
			return None
Exemplo n.º 50
0
def get_exif(image):
    """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
    exif_data = {}
    info = image._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps_data = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]
                exif_data[decoded] = gps_data
            else:
                exif_data[decoded] = value
    return exif_data
Exemplo n.º 51
0
def _get_exif_data(filename):
    """Return a dict with EXIF data."""

    img = PILImage.open(filename)
    exif = img._getexif() or {}
    data = dict((TAGS.get(t, t), v) for (t, v) in exif.items())

    if "GPSInfo" in data:
        gps_data = {}

        for tag in data["GPSInfo"]:
            gps_data[GPSTAGS.get(tag, tag)] = data["GPSInfo"][tag]

        data["GPSInfo"] = gps_data

    return data
Exemplo n.º 52
0
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    logger = logging.getLogger(__name__)
    img = PILImage.open(filename)
    exif = img._getexif() or {}
    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if 'GPSInfo' in data:
        try:
            data['GPSInfo'] = {GPSTAGS.get(tag, tag): value
                            for tag, value in data['GPSInfo'].items()}
        except AttributeError as e:
            logger.debug("No valid GPSInfo data found for %s" % filename)
            del data['GPSInfo']
    return data
Exemplo n.º 53
0
    def _set_exif_gps_data(self, gpsinfo):
        def _get_if_exist(data, key):
            if key in data:
                return data[key]

            return None
    
        def _convert_to_degress(value):
            """Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
            d0 = value[0][0]
            d1 = value[0][1]
            d = float(d0) / float(d1)

            m0 = value[1][0]
            m1 = value[1][1]
            m = float(m0) / float(m1)

            s0 = value[2][0]
            s1 = value[2][1]
            s = float(s0) / float(s1)

            return d + (m / 60.0) + (s / 3600.0)
        
        gps_data = {}
        
        for t in gpsinfo:
            sub_decoded = GPSTAGS.get(t, t)
            gps_data[sub_decoded] = gpsinfo[t]
            
        lat = -1
        lon = -1
        gps_latitude = _get_if_exist(gps_data, 'GPSLatitude')
        gps_latitude_ref = _get_if_exist(gps_data, 'GPSLatitudeRef')
        gps_longitude = _get_if_exist(gps_data, 'GPSLongitude')
        gps_longitude_ref = _get_if_exist(gps_data, 'GPSLongitudeRef')

        if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
            lat = _convert_to_degress(gps_latitude)
            if gps_latitude_ref != "N":
                lat = 0 - lat
            
            lon = _convert_to_degress(gps_longitude)
            if gps_longitude_ref != "E":
                lon = 0 - lon
        
        self.exif_latitude = lat
        self.exif_longitude = lon
Exemplo n.º 54
0
 def getExifData(cls, image):
     exifData = {}
     exifInfo = image._getexif()
     if exifInfo:
         for tagData, value in exifInfo.items():
             keyData = TAGS.get(tagData, tagData)
             if keyData == EXIFGPSINFO:
                 # GPSに関する情報(位置情報など)。階層構造になっている。
                 gpsData = {}
                 for subTagData in value:
                     subKeyData = GPSTAGS.get(subTagData, subTagData)
                     gpsData[subKeyData] = value[subTagData]
                 exifData[keyData] = gpsData
             else:
                 # GPS以外に関する情報(日時情報など)。
                 exifData[keyData] = value
     return exifData
def get_exif_data(image): #Getting EXIF data from image
    exif_data = {}
    info = image._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps_data = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]

                exif_data[decoded] = gps_data
            else:
                exif_data[decoded] = value

    return exif_data
def get_exif_data(image):
	# Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags
	exif_data = {}
	img = Image.open(image)
	info = getattr(img, '_getexif', lambda: None)()
	if info:
		for tag, value in info.items():
			decoded = TAGS.get(tag, tag)
			if decoded == "GPSInfo":
				gps_data = {}
				for t in value:
					sub_decoded = GPSTAGS.get(t, t)
					gps_data[sub_decoded] = value[t]

				exif_data[decoded] = gps_data
			else:
				exif_data[decoded] = value
	return exif_data
Exemplo n.º 57
-1
def getGPSTags(imagePath):
    image = Image.open(imagePath)
    #Get the EXIF data from the image.
    rawEXIF = image._getexif()

    #Somewhere to store the rest of the EXIF data, I might use it one day.
    tags = {}

    #Aaand a place to store the GPS data.
    gpsTags = {}

    #pulling out the EXIF tags.
    for tag, value in rawEXIF.items():
        decoded = TAGS.get(tag,tag)
        tags[decoded] = value

    rawGPS = tags['GPSInfo']

    #Pulling out the GPS specific tags.
    for gpstag , value in rawGPS.items():
        decoded = GPSTAGS.get(gpstag,gpstag)
        gpsTags[decoded] = value

    #Pull together our return variable that includes both tagsets.
    return {'tags' : tags, 'gps' : gpsTags}
Exemplo n.º 58
-1
def get_exif_data(image):
    """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""

    try:
        info = image._getexif()
    except AttributeError:
        return {}
    if not info:
        return {}
    exif_data = {TAGS.get(tag, tag): value for tag, value in info.items()}

    def is_fraction(val):
        return isinstance(val, tuple) and len(val) == 2 and isinstance(val[0], int) and isinstance(val[1], int)

    def frac_to_dec(frac):
        return float(frac[0]) / float(frac[1])

    if "GPSInfo" in exif_data:
        gpsinfo = {GPSTAGS.get(t, t): v for t, v in exif_data["GPSInfo"].items()}
        for tag, value in gpsinfo.items():
            if is_fraction(value):
                gpsinfo[tag] = frac_to_dec(value)
            elif all(is_fraction(x) for x in value):
                gpsinfo[tag] = tuple(map(frac_to_dec, value))
        exif_data["GPSInfo"] = gpsinfo
    return exif_data
Exemplo n.º 59
-1
def get_exif_data(image):
    """
    Returns a dictionary from the exif data of an PIL Image item.
    Also converts the GPS Tags
    https://gist.github.com/valgur/2fbed04680864fab1bfc
    """

    info = image._getexif()
    if not info:
        return {}
    exif_data = {TAGS.get(tag, tag): value for tag, value in info.items()}

    def is_fraction(val):
        return isinstance(val, tuple) and len(val) == 2 and isinstance(
            val[0], int) and isinstance(val[1], int)

    def frac_to_dec(frac):
        return float(frac[0]) / float(frac[1])

    if 'GPSInfo' in exif_data:
        gpsinfo = {GPSTAGS.get(t, t): v
                   for t, v in exif_data['GPSInfo'].items()}
        for tag, value in gpsinfo.items():
            if is_fraction(value):
                gpsinfo[tag] = frac_to_dec(value)
            elif all(is_fraction(x) for x in value):
                gpsinfo[tag] = tuple(map(frac_to_dec, value))
        exif_data['GPSInfo'] = gpsinfo

    return exif_data