照片识别

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_key = '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='C:/Users/pacer/desktop/img/5.jpg')
    address = find_address_from_GPS(GPS=GPS_info)
    print("拍摄时间:" + GPS_info.get("date_information"))
    print('照片拍摄地址:' + str(address))
————————————————
版权声明:本文为优快云博主「L e x」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_42350212/article/details/116568510

要在 Android 应用中实现照片识别功能,可以通过使用 Google 的 ML Kit 或其他机器学习框架来完成。ML Kit 提供了预训练的模型,能够轻松集成到 Android 应用中,用于图像识别、文本识别、条形码扫描等功能。 ### 实现步骤 #### 1. 添加必要的依赖项 在 `build.gradle` 文件中添加 ML Kit 和其他必要的依赖项。例如,使用 ML Kit 的图像识别功能需要添加以下依赖项: ```gradle implementation 'com.google.mlkit:mlkit-vision-image:16.0.0' implementation 'com.google.mlkit:mlkit-text:16.0.0' ``` 这些依赖项允许应用加载图像并使用 ML Kit 进行文本识别和图像分析 [^2]。 #### 2. 请求必要的权限 在 `AndroidManifest.xml` 文件中添加必要的权限,以便应用可以访问设备的相机和存储: ```xml <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ``` 这些权限允许应用访问相机和外部存储,以便拍摄照片或从相册中选择照片进行识别 [^3]。 #### 3. 创建图像识别功能 创建一个方法来处理图像识别。例如,使用 ML Kit 的 `TextRecognition` 功能来识别图像中的文本: ```java public void recognizeTextFromImage(Bitmap bitmap) { Image mediaImage = Image.fromBitmap(bitmap); TextRecognizer recognizer = TextRecognition.getClient(); Task<Text> result = recognizer.process(mediaImage) .addOnSuccessListener(visionText -> { // Task completed successfully for (Text.TextBlock block : visionText.getTextBlocks()) { String text = block.getText(); Log.d("RecognizedText", text); } }) .addOnFailureListener(e -> { // Task failed with an exception Log.e("RecognizedText", "Error: " + e.getMessage()); }); } ``` 此代码片段展示了如何使用 ML Kit 识别图像中的文本,并将其打印到日志中 [^4]。 #### 4. 集成用户界面 创建一个用户界面,允许用户选择照片或拍摄照片,并显示识别结果。例如,使用 `Intent` 启动相机或相册: ```java private static final int REQUEST_IMAGE_CAPTURE = 1; private static final int REQUEST_IMAGE_PICK = 2; public void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } public void pickImageFromGallery() { Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(pickIntent, REQUEST_IMAGE_PICK); } ``` 这些方法允许用户选择拍摄照片或从相册中选择照片,并在应用中处理所选图像 [^3]。 #### 5. 处理用户选择的图像 在 `onActivityResult` 方法中处理用户选择的图像,并调用图像识别方法: ```java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { Bitmap bitmap = null; if (requestCode == REQUEST_IMAGE_CAPTURE) { Bundle extras = data.getExtras(); bitmap = (Bitmap) extras.get("data"); } else if (requestCode == REQUEST_IMAGE_PICK) { Uri selectedImage = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage); } catch (IOException e) { e.printStackTrace(); } } if (bitmap != null) { recognizeTextFromImage(bitmap); } } } ``` 此方法处理用户选择的照片,并调用 `recognizeTextFromImage` 方法进行图像识别 [^4]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值