使用Python从图像中提取gps坐标

问题描述 投票:0回答:3

代码:

from PIL import Image
from PIL.ExifTags import TAGS

# path to the image or video
imagename = "image.jpg"

# read the image data using PIL
image = Image.open(imagename)

# extract EXIF data
exifdata = image.getexif()

# iterating over all EXIF data fields
for tag_id in exifdata:
    # get the tag name, instead of human unreadable tag id
    tag = TAGS.get(tag_id, tag_id)
    data = exifdata.get(tag_id)
    # decode bytes
    if isinstance(data, bytes):
        data = data.decode()
    print(f"{tag:25}: {data}")

输出:

ExifVersion              : 0220
ComponentsConfiguration  : 
ShutterSpeedValue        : (1345, 100)
DateTimeOriginal         : 2020:08:27 09:43:15
DateTimeDigitized        : 2020:08:27 09:43:15
ApertureValue            : (185, 100)
BrightnessValue          : (930, 100)
ExposureBiasValue        : (0, 10)
MaxApertureValue         : (185, 100)
MeteringMode             : 2
Flash                    : 0
FocalLength              : (358, 100)
UserComment              : 
ColorSpace               : 1
ExifImageWidth           : 4128
SceneCaptureType         : 0
SubsecTime               : 0424
SubsecTimeOriginal       : 0424
SubsecTimeDigitized      : 0424
ExifImageHeight          : 1908
ImageLength              : 1908
Make                     : samsung
Model                    : SM-M305F
Orientation              : 6
YCbCrPositioning         : 1
ExposureTime             : (1, 2786)
ExifInteroperabilityOffset: 944
XResolution              : (72, 1)
FNumber                  : (190, 100)
SceneType                : 
YResolution              : (72, 1)
ImageUniqueID            : E13LLLI00PM E13LLMK03PA

ExposureProgram          : 2
CustomRendered           : 0
ISOSpeedRatings          : 40
ResolutionUnit           : 2
ExposureMode             : 0
FlashPixVersion          : 0100
ImageWidth               : 4128
WhiteBalance             : 0
Software                 : M305FDDU5CTF2
DateTime                 : 2020:08:27 09:43:15
DigitalZoomRatio         : (0, 0)
FocalLengthIn35mmFilm    : 27
Contrast                 : 0
Saturation               : 0
Sharpness                : 0
ExifOffset               : 226
MakerNote                : 0100 Z@P

如何从图像中获取坐标点详细信息(纬度和经度)?

python geolocation exif
3个回答
4
投票

使用piexif模块(

pip install piexif
)你可以获取exif中的GPS信息,如下所示。

from pprint import pprint
from PIL import Image
import piexif

codec = 'ISO-8859-1'  # or latin-1

def exif_to_tag(exif_dict):
    exif_tag_dict = {}
    thumbnail = exif_dict.pop('thumbnail')
    exif_tag_dict['thumbnail'] = thumbnail.decode(codec)

    for ifd in exif_dict:
        exif_tag_dict[ifd] = {}
        for tag in exif_dict[ifd]:
            try:
                element = exif_dict[ifd][tag].decode(codec)

            except AttributeError:
                element = exif_dict[ifd][tag]

            exif_tag_dict[ifd][piexif.TAGS[ifd][tag]["name"]] = element

    return exif_tag_dict

def main():
    filename = 'IMG_2685.jpg'  # obviously one of your own pictures
    im = Image.open(filename)

    exif_dict = piexif.load(im.info.get('exif'))
    exif_dict = exif_to_tag(exif_dict)

    pprint(exif_dict['GPS'])

if __name__ == '__main__':
   main()

结果

{'GPSAltitude': (94549, 14993),
 'GPSAltitudeRef': 0,
 'GPSDateStamp': '2020:09:04',
 'GPSDestBearing': (1061399, 5644),
 'GPSDestBearingRef': 'T',
 'GPSHPositioningError': (5, 1),
 'GPSImgDirection': (1061399, 5644),
 'GPSImgDirectionRef': 'T',
 'GPSLatitude': ((12, 1), (34, 1), (1816, 100)),
 'GPSLatitudeRef': 'N',
 'GPSLongitude': ((99, 1), (57, 1), (4108, 100)),
 'GPSLongitudeRef': 'E',
 'GPSSpeed': (0, 1),
 'GPSSpeedRef': 'K',
 'GPSTimeStamp': ((13, 1), (2, 1), (4599, 100)),
 'GPSVersionID': (2, 2, 0, 0)}

这里

exif_to_tag
将 exif 代码转换为更易读的标签。


2
投票

使用此模块您可以获取信息。

pip install exif

那就使用这个代码吧!

from exif import Image

def decimal_coords(coords, ref):
    decimal_degrees = coords[0] + coords[1] / 60 + coords[2] / 3600
    if ref == "S" or ref =='W' :
        decimal_degrees = -decimal_degrees
    return decimal_degrees

def image_coordinates(image_path):

    with open(image_path, 'rb') as src:
        img = Image(src)
    if img.has_exif:
        try:
            img.gps_longitude
            coords = (decimal_coords(img.gps_latitude,
                      img.gps_latitude_ref),
                      decimal_coords(img.gps_longitude,
                      img.gps_longitude_ref))
        except AttributeError:
            print ('No Coordinates')
    else:
        print ('The Image has no EXIF information')
        
    return({"imageTakenTime":img.datetime_original, "geolocation_lat":coords[0],"geolocation_lng":coords[1]})

image_coordinates('Your image path')

结果

{'imageTakenTime': '2012:04:22 16:51:08',
 'geolocation_lat': 52.314166666666665,
 'geolocation_lng': 4.941}


0
投票

使用此代码

from PIL import ExifTags, Image


def decimal_coords(coords, ref):
    decimal_degrees = float(coords[0]) + float(coords[1]) / 60 + float(coords[2]) / 3600
    if ref == "S" or ref =='W' :
        decimal_degrees = -1 * decimal_degrees
    return decimal_degrees


GPSINFO_TAG = next(
    tag for tag, name in TAGS.items() if name == "GPSInfo"
)

path = r"YOUR IMAGE.JPG"
image = Image.open(path)
info = image.getexif()

gpsinfo = info.get_ifd(GPSINFO_TAG)


print('Lat : {0}'.format(decimal_coords(gpsinfo[2], gpsinfo[1])))
print('Lon : {0}'.format(decimal_coords(gpsinfo[4], gpsinfo[3])))
print('Alt : {0}'.format(gpsinfo[6]))

结果:

Lat : 6.504368527777777
Lon : -70.76050111111111
Alt : 229.017
© www.soinside.com 2019 - 2024. All rights reserved.