从python中的照片解释exif数据的GPS信息

时间:2013-11-06 05:27:56

标签: python gps python-imaging-library exif

我正在写一个小程序来获取iphone jpg照片的GPS信息。

我使用的库是python中的PIL。现在我可以获得GPSInfo,类似于:

{1: 'N', 
 2: ((1, 1), (20, 1), (5365, 100)), 
 3: 'E', 
 4: ((103, 1), (41, 1), (1052, 100)), 
 5: 0, 
 6: (43, 1), 
 7: ((15, 1), (32, 1), (7, 1)), 
 16: 'T', 
 17: (77473, 452), 
 29: '2013:10:25'}

我怎么解释这个?我注意到标签不是连续的,所以我可以参考哪些作弊表,以便更好地理解所有数字标签及其含义?谢谢!

更新

对不起,我已经弄明白了。在PIL lib中,有一个GPSTAGS.get()函数可以帮助我解码gps信息中的密钥。谢谢你们!

gpsinfo = {}
for key in exif['GPSInfo'].keys():
    decode = ExifTags.GPSTAGS.get(key,key)
    gpsinfo[decode] = exif['GPSInfo'][key]
print gpsinfo

这是结果

{'GPSTimeStamp': ((15, 1), (32, 1), (7, 1)), 
 'GPSImgDirectionRef': 'T', 
 'GPSImgDirection': (77473, 452), 
 'GPSLongitude': ((103, 1), (41, 1), (1052, 100)), 
 'GPSLatitudeRef': 'N', 29: '2013:10:25', 
 'GPSAltitude': (43, 1), 
 'GPSLatitude': ((1, 1), (20, 1), (5365, 100)), 
 'GPSLongitudeRef': 'E', 
 'GPSAltitudeRef': 0}

3 个答案:

答案 0 :(得分:12)

使用exifread模块。

这是一个非常有用的gist

import exifread as ef


# barrowed from 
# https://gist.github.com/snakeye/fdc372dbf11370fe29eb 
def _convert_to_degress(value):
    """
    Helper function to convert the GPS coordinates stored in the EXIF to degress in float format
    :param value:
    :type value: exifread.utils.Ratio
    :rtype: float
    """
    d = float(value.values[0].num) / float(value.values[0].den)
    m = float(value.values[1].num) / float(value.values[1].den)
    s = float(value.values[2].num) / float(value.values[2].den)

    return d + (m / 60.0) + (s / 3600.0)


def getGPS(filepath):
    '''
    returns gps data if present other wise returns empty dictionary
    '''
    with open(filepath, 'r') as f:
        tags = ef.process_file(f)
        latitude = tags.get('GPS GPSLatitude')
        latitude_ref = tags.get('GPS GPSLatitudeRef')
        longitude = tags.get('GPS GPSLongitude')
        longitude_ref = tags.get('GPS GPSLongitudeRef')
        if latitude:
            lat_value = _convert_to_degress(latitude)
            if latitude_ref.values != 'N':
                lat_value = -lat_value
        else:
            return {}
        if longitude:
            lon_value = _convert_to_degress(longitude)
            if longitude_ref.values != 'E':
                lon_value = -lon_value
        else:
            return {}
        return {'latitude': lat_value, 'longitude': lon_value}
    return {}


file_path = 'file path of the file'    
gps = getGPS(file_path)
print gps

答案 1 :(得分:6)

最新答案,但是从 2019 开始,您可以使用GPSPhoto,即:

    render(){
    let users = this.props.chatkit.roomUsers
    let userIds = users.map((user) => {
        return user.id
    })
    let roomMessages = this.props.messages
    let messages = []
    for(var i = 0; i < roomMessages.length; i++){
        //create a new field to give each message a unique id
        roomMessages[i].unique = roomMessages[i].senderId
        //create a new field to give each message the avatar from that user
        let matchingUserIndex = userIds.indexOf(roomMessages[i].senderId)
        if(matchingUserIndex >= 0){
            roomMessages[i].avatar = users[matchingUserIndex].avatar
        }

        //review messages
        let previous = {}
        if(i > 0){
            previous = roomMessages[i - 1]
        }
        let currentMessage = roomMessages[i]
        //check if consecutive messages are made by the same user
        if(currentMessage.senderId === previous.senderId && currentMessage.unique === previous.unique){
            //display user name and avatar as an empty string
            messages.push({...currentMessage, unique: "", avatar: ""})
        } else{
            //display the user name
            messages.push({...currentMessage})
        }
    }
    //transform the unique field to contain the name of the user 
    let updatedMessages = []
    for(var j = 0; j < messages.length; j++){
        let matchingIdIndex = userIds.indexOf(messages[j].unique)
        if(matchingIdIndex >= 0 && messages[j].unique !== ""){
            messages[j].unique = users[matchingIdIndex].name
            updatedMessages.push(messages[j])
        } else {
            updatedMessages.push(messages[j])
        }
    }

    let currentChatkitUser = this.props.chatkit.chatUser.id

    return(
        <div>
            {this.props.room && (
                <div 
                    style={{overflow: "scroll", overflowX: "hidden", maxHeight: "70vh"}}
                    ref={this.messageList}
                >
                    <ul style={{listStyle: "none"}} className="p-4 mb-0">
                        {updatedMessages.map((message, index) => {
                            return (
                                <li 
                                    className="mb-1"
                                    key={index}>
                                    <div>
                                        {message.unique && (
                                            <span 
                                                className="d-block font-weight-bold mt-3"
                                                style={{color: "#000323"}}
                                            >
                                                <img 
                                                    src={message.avatar} 
                                                    style={{width: "2.5rem"}}
                                                    className="rounded-circle mr-2"
                                                />
                                                {message.unique}
                                            </span>
                                        )}
                                        <span 
                                            className={message.senderId === currentChatkitUser ? 
                                                "muted-blue text-light rounded d-inline-block ml-5" : "bg-secondary text-light rounded d-inline-block ml-5" 
                                            }
                                            style={{padding:".25rem .5rem"}}
                                        >
                                            {message.text}
                                        </span>
                                    </div>
                                </li>
                            )
                        })}
                    </ul>
                    <TypingIndicator usersWhoAreTyping={this.props.usersWhoAreTyping}/>
                    <div 
                        style={{float: "left", clear: "both"}}
                        ref={this.messagesEnd}>     
                    </div>
                </div>
            )}
        </div>
    )
}

输出:

38.71615498471598 -9.148730635643007


安装:

from GPSPhoto import gpsphoto
# Get the data from image file and return a dictionary
data = gpsphoto.getGPSData('IMG_20181224_201933.jpg')
print(data['Latitude'], data['Longitude'])

答案 2 :(得分:5)

OP已经发布了使用PIL的解决方案。如果您想从Python获取GPS信息,可以使用exifread

获取

使用pip安装包

$ pip install exifread

获取GPS数据

In [10]: import exifread

In [11]: tags = exifread.process_file(open('./tests/demo-project/content/test.jpg', 'rb'))                                              

In [12]: geo = {i:tags[i] for i in tags.keys() if i.startswith('GPS')}

In [13]: geo
Out[13]: 
{'GPS GPSAltitude': (0x0006) Ratio=186188/239 @ 898,
 'GPS GPSAltitudeRef': (0x0005) Byte=0 @ 722,
 'GPS GPSDate': (0x001D) ASCII=2015:12:06 @ 954,
 'GPS GPSDestBearing': (0x0018) Ratio=43771/526 @ 946,
 'GPS GPSDestBearingRef': (0x0017) ASCII=T @ 806,
 'GPS GPSImgDirection': (0x0011) Ratio=43771/526 @ 938,
 'GPS GPSImgDirectionRef': (0x0010) ASCII=T @ 782,
 'GPS GPSLatitude': (0x0002) Ratio=[46, 3803/100, 0] @ 850,
 'GPS GPSLatitudeRef': (0x0001) ASCII=N @ 674,
 'GPS GPSLongitude': (0x0004) Ratio=[13, 2429/100, 0] @ 874,
 'GPS GPSLongitudeRef': (0x0003) ASCII=E @ 698,
 'GPS GPSSpeed': (0x000D) Ratio=139/50 @ 930,
 'GPS GPSSpeedRef': (0x000C) ASCII=K @ 758,
 'GPS GPSTimeStamp': (0x0007) Ratio=[10, 37, 33] @ 906,
 'GPS Tag 0x001F': (0x001F) Ratio=30 @ 966}