如何用python获取到照片拍摄时的详细位置(附源码)

目录
  • 一.引言
    • 1.读取照片信息,获取坐标
    • 2.通过baidu Map的API将GPS信息转换成地址。
  • 二.源码附上!!!
  • 注意事项
  • 总结

一.引言

先看获取到的效果

拍摄时间:2021:12:18 16:22:13
照片拍摄地址:('内蒙古自治区包头市昆都仑区', '内蒙古自治区', '包头市', '昆都仑区', '多米幼儿园东南360米')

我们的女朋友给我们发来一张照片我们如何获取到她的位置呢?

用手机拍照会带着GPS信息,原来没注意过这个,因此查看下并使用代码获取照片里的GPS信息

查看图片文件属性

1.读取照片信息,获取坐标

ExifRead

Python library to extract EXIF data from tiff and jpeg files.

安装

pip install exifread

读取GPS

import exifread
import re

def read():
    GPS = {}
    date = ''
    f = open("C:\\Users\\24190\\Desktop\\小朱学长.jpg",'rb')
    contents = exifread.process_file(f)
    for key in contents:
        if key == "GPS GPSLongitude":
            print("经度 =", contents[key],contents['GPS GPSLatitudeRef'])
        elif key =="GPS GPSLatitude":
            print("纬度 =",contents[key],contents['GPS GPSLongitudeRef'])
        #print(contents)
read()

运行

我们得到了一个简易的gps地址

如果想要读取全部的拍摄信息:

# 读取照片的GPS经纬度信息
def find_GPS_image(pic_path):
        GPS = {}
        date = ''
        with open(pic_path, 'rb') as f:
                tags = exifread.process_file(f)
                for tag, value in tags.items():
                        # 纬度
                        if re.match('GPS GPSLatitudeRef', tag):
                                GPS['GPSLatitudeRef'] = str(value)
                        # 经度
                        elif re.match('GPS GPSLongitudeRef', tag):
                                GPS['GPSLongitudeRef'] = str(value)
                        # 海拔
                        elif re.match('GPS GPSAltitudeRef', tag):
                                GPS['GPSAltitudeRef'] = str(value)
                        elif re.match('GPS GPSLatitude', tag):
                                try:
                                        match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                                        GPS['GPSLatitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
                                except:
                                        deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
                                        GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
                        elif re.match('GPS GPSLongitude', tag):
                                try:
                                        match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                                        GPS['GPSLongitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
                                except:
                                        deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
                                        GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
                        elif re.match('GPS GPSAltitude', tag):
                                GPS['GPSAltitude'] = str(value)
                        elif re.match('.*Date.*', tag):
                                date = str(value)
        return {'GPS_information': GPS, 'date_information': date}

2.通过baidu Map的API将GPS信息转换成地址。

众所周知gps和百度的经纬度会有误差,那么我们需要调用百度转换接口,这个百度目前没有开源。

# 通过baidu Map的API将GPS信息转换成地址。
def find_address_from_GPS(GPS):
        """
        使用Geocoding API把经纬度坐标转换为结构化地址。
        :param GPS:
        :return:
        """
        secret_k ey = 'XXX'
        if not GPS['GPS_information']:
                return '该照片无GPS信息'
        lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
        baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(
                secret_key, lat, lng)
        response = requests.get(baidu_map_api)
        content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
        print(content)
        baidu_map_address = json.loads(content)
        formatted_address = baidu_map_address["result"]["formatted_address"]
        province = baidu_map_address["result"]["addressComponent"]["province"]
        city = baidu_map_address["result"]["addressComponent"]["city"]
        district = baidu_map_address["result"]["addressComponent"]["district"]
        location = baidu_map_address["result"]["sematic_description"]
        return formatted_address, province, city, district, location

然后在主函数输出:

二.源码附上!!!

# coding=utf-8
import exifread
import re
import json
import requests
import os

# 转换经纬度格式
def latitude_and_longitude_convert_to_decimal_system(*arg):
        """
        经纬度转为小数, param arg:
        :return: 十进制小数
        """
        return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)

# 读取照片的GPS经纬度信息
def find_GPS_image(pic_path):
        GPS = {}
        date = ''
        with open(pic_path, 'rb') as f:
                tags = exifread.process_file(f)
                for tag, value in tags.items():
                        # 纬度
                        if re.match('GPS GPSLatitudeRef', tag):
                                GPS['GPSLatitudeRef'] = str(value)
                        # 经度
                        elif re.match('GPS GPSLongitudeRef', tag):
                                GPS['GPSLongitudeRef'] = str(value)
                        # 海拔
                        elif re.match('GPS GPSAltitudeRef', tag):
                                GPS['GPSAltitudeRef'] = str(value)
                        elif re.match('GPS GPSLatitude', tag):
                                try:
                                        match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                                        GPS['GPSLatitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
                                except:
                                        deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
                                        GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
                        elif re.match('GPS GPSLongitude', tag):
                                try:
                                        match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                                        GPS['GPSLongitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
                                except:
                                        deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
                                        GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
                        elif re.match('GPS GPSAltitude', tag):
                                GPS['GPSAltitude'] = str(value)
                        elif re.match('.*Date.*', tag):
                                date = str(value)
        return {'GPS_information': GPS, 'date_information': date}

# 通过baidu Map的API将GPS信息转换成地址。
def find_address_from_GPS(GPS):
        """
        使用Geocoding API把经纬度坐标转换为结构化地址。
        :param GPS:
        :return:
        """
        secret_ke y = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'
        if not GPS['GPS_information']:
                return '该照片无GPS信息'
        lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
        baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(
                secret_key, lat, lng)
        response = requests.get(baidu_map_api)
        content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
        print(content)
        baidu_map_address = json.loads(content)
        formatted_address = baidu_map_address["result"]["formatted_address"]
        province = baidu_map_address["result"]["addressComponent"]["province"]
        city = baidu_map_address["result"]["addressComponent"]["city"]
        district = baidu_map_address["result"]["addressComponent"]["district"]
        location = baidu_map_address["result"]["sematic_description"]
        return formatted_address, province, city, district, location

if __name__ == '__main__':
        GPS_info = find_GPS_image(pic_path='小朱学长.jpg')
        address = find_address_from_GPS(GPS=GPS_info)
        print("拍摄时间:" + GPS_info.get("date_information"))
        print('照片拍摄地址:' + str(address))

注意事项

1.照片的地址信息等,一般的手机相机默认是打开的。

2.微信和QQ里面发送原图,信息都会完整的保留下来。

3.代码里面需要处理在照片我放到了代码的同文件夹下,所以没有写路径,大家可以自己写路径,或者放到于代码相同的路径下即可。

总结

到此这篇关于如何用python获取到照片拍摄时的详细位置的文章就介绍到这了,更多相关python获取照片详细位置内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python根据照片获取地理位置及泄露防御

    首先,说明一下python确实可以根据照片获取地理位置,但是也是有一定的限制条件的. 获取照片地理位置的实现思路是这样的: 通过提取照片中的经纬度信息. 然后通过经纬度信息找到具体的地理位置信息. 安装可以读取经纬度信息的python非标准库exifread pip install exifread 将该模块导入到当前代码块中. import exifread as ex 编写照片信息读取函数,获取照片中的经纬度信息. def read_image(): ''' 经纬度信息读取函数 :retur

  • 利用Python实现获取照片位置信息

    目录 引言 一.exifread函数库 安装exrfread库(PyCharm) 什么是exifread函数库 二.获取女朋友发来的照片(单身勿扰) 三.具体代码实现 四.经纬度转换 引言 通过一张照片居然发现女友在宿舍里没去上课!强大的照片位置信息获取,快来一起学习吧! 一.exifread函数库 要怎样获得拍摄图片的GPS呢?这里我们需要exifread 库,这个就是用来提取 GPS 信息的.直接 pip install exifread 来安装就好了. 安装exrfread库(PyChar

  • 基于Python获取照片的GPS位置信息

    这篇文章主要介绍了基于Python获取照片的GPS位置信息,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 昨天听人说,用手机拍照会带着GPS信息,原来没注意过这个,因此查看下并使用代码获取照片里的GPS信息 查看图片文件属性 说明: 一般手机拍照时默认会打开地理位置开关 经过压缩后,通常会将GPS信息压缩掉 EXIF 可交换图像文件常被简称为EXIF(Exchangeable image file format),是专门为数码相机的照片设定的,

  • 如何用python获取到照片拍摄时的详细位置(附源码)

    目录 一.引言 1.读取照片信息,获取坐标 2.通过baidu Map的API将GPS信息转换成地址. 二.源码附上!!! 注意事项 总结 一.引言 先看获取到的效果 拍摄时间:2021:12:18 16:22:13照片拍摄地址:('内蒙古自治区包头市昆都仑区', '内蒙古自治区', '包头市', '昆都仑区', '多米幼儿园东南360米') 我们的女朋友给我们发来一张照片我们如何获取到她的位置呢? 用手机拍照会带着GPS信息,原来没注意过这个,因此查看下并使用代码获取照片里的GPS信息 查看图

  • python基于tkinter制作无损音乐下载工具(附源码)

    继续写GUI,本次依然使用Tkinter设计一款图形界面,使用Tkinter做一款音乐下载软件,听起来听平常的,但是我这款软件能够下载 无损音乐下载软件,听起来不错吧,Let`s go! 一.准备工作 python Tkinter 二.预览 1.搜索 2.下载 3.结果 无损音乐就这样下载完了. 三.详细设计 这里仅展示我设计的整体思路. 四.源代码 4.1 Music_Search-v1.0.py from tkinter import * from tkinter import ttk fr

  • Python爬虫实战之虎牙视频爬取附源码

    目录 知识点 开发环境 分析目标url 开始代码 最开始还是线导入所需模块 数据请求 获取视频标题以及url地址 获取视频id 保存数据 调用函数 运行代码,得到数据 知识点 爬虫基本流程 re正则表达式简单使用 requests json数据解析方法 视频数据保存 开发环境 Python 3.8 Pycharm 爬虫基本思路流程: (重点) [无论任何网站 任何数据内容 都是按照这个流程去分析] 1.确定需求 (爬取的内容是什么东西?) 都通过开发者工具进行抓包分析 分析视频播放url地址 是

  • Python写一个简单上课点名系统(附源码)

    目录 一.准备工作 1.Tkinter 2.PIL 二.预览 1.启动 2.开始点名-顺序点名 3.开始点名-随机点名 4.手动加载人名单 5.开始点名-顺序点名-Pyqt5版本 三.思路 1.整体实现思路 2.点名实现思路 四.源代码 五.总结 一.准备工作 1.Tkinter Tkinter 是 python 内置的 TK GUI 工具集.TK 是 Tcl 语言的原生 GUI 库.作为 python 的图形设计工具,它所使用的 Tcl 语言环境已经完全嵌入到了 python 解释器中. 我们

  • 使用Python做垃圾分类的原理及实例代码附源码

    0 引言 纸巾再湿也是干垃圾?瓜子皮再干也是湿垃圾??最近大家都被垃圾分类折磨的不行,傻傻的你是否拎得清?

  • 微信小程序获取手机网络状态的方法【附源码下载】

    本文实例讲述了微信小程序获取手机网络状态的方法.分享给大家供大家参考,具体如下: 1.效果展示 2.关键代码 index.wxml布局文件代码 <view>手机网络状态:{{netWorkType}}</view> index.js逻辑文件代码 Page({ data: { netWorkType:'' }, onLoad: function () { var that=this wx.getNetworkType({ success: function(res) { that.s

  • Python基于pygame实现的弹力球效果(附源码)

    本文实例讲述了Python基于pygame实现的弹力球效果.分享给大家供大家参考,具体如下: 运行效果: 代码部分如下: #A bouncing ball import sys, pygame __author__ = {'name' : 'Hongten', 'mail' : 'hongtenzone@foxmail.com', 'QQ' : '648719819', 'Version' : '1.0'} pygame.init() size = width, height = 600, 50

  • Python基于pygame实现的font游戏字体(附源码)

    本文实例讲述了Python基于pygame实现的font游戏字体.分享给大家供大家参考,具体如下: 在pygame游戏开发中,一个友好的UI中,漂亮的字体是少不了的 今天就给大伙带来有关pygame中字体的一些介绍说明 首先我们得判断一下我们的pygame中有没有font这个模块 复制代码 代码如下: if not pygame.font: print('Warning, fonts disabled') 如果有的话才可以进行接下来的操作:-) 我们可以这样使用pygame中的字体: 复制代码

  • Python动刷新抢12306火车票的代码(附源码)

    用python另一个抢票神器,你get到了吗? 2017年时间飞逝,转眼间距离2018年春节还有不到1个月的时间,还在为抢不到火车票发愁吗?作为程序员的我们撸一个抢票软件可好? 难以想象的数据,预示着今年春运回程和返程车票 购买难度将进一步加大- 抢购车票怕是比李白跨越"蜀道"的难度还大哦~ 当你想查询一下火车票信息的时候,还在为打开无响应的12306官网和广告n秒的APP吗而懊恼吗? 不如用 Python 写一个命令行版的火车票查看器, 只要在命令行敲一行命令就能获得你想要的火车票信

  • Python实现淘宝秒杀聚划算抢购自动提醒源码

    说明 本实例能够监控聚划算的抢购按钮,在聚划算整点聚的时间到达时发出提醒(音频文件自己定义位置)并自动弹开页面(URL自己定义). 同时还可以通过命令行参数自定义刷新间隔时间(默认0.1s)和监控持续时间(默认1800s). 源码 # encoding: utf-8 ''''' @author: Techzero @email: techzero@163.com @time: 2014-5-18 下午5:06:29 ''' import cStringIO import getopt impor

随机推荐