Azure的AI使用-(语言检测、图像分析、图像文本识别)

1.语言检测

安装包:

# 语言检测
%pip install azure-ai-textanalytics==5.2.0

需要用到密钥和资源的终结点,所以去Azure上创建资源,我这个是创建好的了然后点击密钥和终结者去拿到key和终结点

两个密钥选择哪个都行 

语言检测代码示例: 

key = ""
endpoint = ""
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

def authenticate_client():
    ta_credential= AzureKeyCredential(key)
    text_analytics_client=TextAnalyticsClient(
        endpoint=endpoint,
        credential=ta_credential
    )
    return text_analytics_client
    
client=authenticate_client();

# 检测文本是哪种语言
def language_detection_example():
    try:
        documents = ["Ce document est rédigé en Français."]
        response=client.detect_language(documents=documents,country_hint = 'us')[0]
        print("response",response)
        print("Language: ", response.primary_language.name)

    except Exception as err:
        print("Encountered exception. {}".format(err))
language_detection_example()

运行结果:

response {'id': '0', 'primary_language': DetectedLanguage(name=French, iso6391_name=fr, confidence_score=1.0), 'warnings': [], 'statistics': None, 'is_error': False, 'kind': 'LanguageDetection'}
Language:  French

2.提取关键短语

# 提取关键语言
def key_phrase_extraction_example(client):

    try:
        documents = ["你好啊,我叫feng,是java程序员,想学习更多的知识"]

        response = client.extract_key_phrases(documents = documents)[0]

        if not response.is_error:
            print("\tKey Phrases:")
            for phrase in response.key_phrases:
                print("\t\t", phrase)
        else:
            print(response.id, response.error)

    except Exception as err:
        print("Encountered exception. {}".format(err))

key_phrase_extraction_example(client)

 返回:感觉对中文的提取一般不是很友好

Key Phrases:
		 feng
		 java程
		 你好
		 想学
		 多的知识

换成英文 

documents = ["Dr. Smith has a very modern medical office, and she has great staff."]

 关键字提取好像就会好很多啊!

 ["Hello, my name is Feng. My hobby is singing and traveling, and I hope to make friends with you"]

确实英语就好很多。 

 

2.图像分析

安装包:

# 图像分析
%pip install --upgrade azure-cognitiveservices-vision-computervision
# 图像处理库
%pip install pillow

这是3.2版本的,这个版本可以支持返回分析中国语言

它就是给一个图片,它会分析出图片大概有什么,以及占的比例,就像是百度的识别万物一样,识别出的物品是什么以及占比。

2.1 url图片地址分析-版本3.2

咱们拿这个图片让它帮分析一下

代码示例: 

# 图像分析-url版本
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
import os

os.environ["VISION_KEY"]=''
os.environ["VISION_ENDPOINT"]=''
subscription_key = os.environ["VISION_KEY"]
endpoint = os.environ["VISION_ENDPOINT"]
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

remote_image_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/landmark.jpg"
tags_result_remote = computervision_client.tag_image(remote_image_url,language="zh")
if (len(tags_result_remote.tags) == 0):
    print("No tags detected.")
else:
    for tag in tags_result_remote.tags:
        print("'{}' with confidence {:.2f}%".format(tag.name, tag.confidence * 100))
print()

运行结果:

 2.2 本地图片分析-版本3.2

# 图像分析-本地图片
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
import os

os.environ["VISION_KEY"]=''
os.environ["VISION_ENDPOINT"]=''
subscription_key = os.environ["VISION_KEY"]
endpoint = os.environ["VISION_ENDPOINT"]
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

local_image_path = os.path.join("C:\\Users\\Uniigym3\\AppData\\Roaming\\Python\\Python38\\Scripts\\images", "11.png")
local_image = open(local_image_path, "rb")
tags_result_local_image = computervision_client.analyze_image_in_stream(local_image,language="zh")
print(tags_result_local_image)
if (len(tags_result_local_image.categories) == 0):
     print("No description detected.")
else:
    for category  in tags_result_local_image.categories:
        print("'{}' with confidence {:.2f}%".format(category.name, category.score  * 100))
print()

运行结果:

 2.3 url图片地址分析-版本4.0

安装包:

%pip install azure-ai-vision

咱们让它分析这个图片

import os
import azure.ai.vision as sdk

service_options = sdk.VisionServiceOptions("",
                                           "")

vision_source = sdk.VisionSource(
    url="https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png")
analysis_options = sdk.ImageAnalysisOptions()
# 可选的视觉特征
analysis_options.features = (
    sdk.ImageAnalysisFeature.CAPTION |
    sdk.ImageAnalysisFeature.TEXT
)
analysis_options.language = "en"
# 性别中立的描述文字,默认值为区分性别的描述文字。 例如,在英语中,当你选择性别中立的描述文字时,“女性”或“男性”等术语将替换为“人员”,而“男孩”或“女孩”则将替换为“儿童”。
analysis_options.gender_neutral_caption = False
image_analyzer = sdk.ImageAnalyzer(service_options, vision_source, analysis_options)
result = image_analyzer.analyze()
# 成功你就按自己选的特征进行
if result.reason == sdk.ImageAnalysisResultReason.ANALYZED:
    if result.caption is not None:
        print(" Caption:")
        print("   '{}', Confidence {:.4f}".format(result.caption.content, result.caption.confidence))
    if result.text is not None:
        print(" Text:")
        for line in result.text.lines:
            points_string = "{" + ", ".join([str(int(point)) for point in line.bounding_polygon]) + "}"
            print("   Line: '{}', Bounding polygon {}".format(line.content, points_string))

else:
     error_details = sdk.ImageAnalysisErrorDetails.from_result(result)
     print("   Error reason: {}".format(error_details.reason))
     print("   Error code: {}".format(error_details.error_code))
     print("   Error message: {}".format(error_details.message))

运行结果:除图片的信息展示以外还会反馈出图片的文字 

analysis_options.gender_neutral_caption = True ,性别中立的描述文字,默认值为区分性别的描述文字。 例如,在英语中,当你选择性别中立的描述文字时,“女性”或“男性”等术语将替换为“人员”,而“男孩”或“女孩”则将替换为“儿童”。

如果设置False或不加这个设置,刚才的结果就是

Caption:
   'a man pointing at a screen', Confidence 0.7768

2.4 本地图片分析-版本4.0

就只需要把上面的这个url图片的代码改成下面的图片路径代码就可以直接在本地使用了。

vision_source = sdk.VisionSource(url="https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png")
vision_source = sdk.VisionSource(filename="C:\\Users\\Uniigym3\\AppData\\Roaming\\Python\\Python38\\Scripts\\images\\test.jpg")

我们测试个百变小樱魔术卡

运行结果:

说是有卡通的小女孩,并且标签也识别出日本动漫。 

再来测试个图片:好几个国家的语言哈

 运行结果:都能轻松的识别出来

官网图片示例:多种图片https://github.com/Azure-Samples/cognitive-services-sample-data-files/tree/master/ComputerVision/Images

图像分析3.2版本git示例:https://github.com/Azure-Samples/cognitive-services-quickstart-code/blob/master/python/ComputerVision/ImageAnalysisQuickstart.py

3.图像OCR文本识别

3.1 url图像地址识别

用这个图片来测试下

#OCR文本识别
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
import time

computervision_client = ComputerVisionClient(You endpoint, 
                                             CognitiveServicesCredentials(Your key))
read_image_url = "https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png"
read_response = computervision_client.read(read_image_url,  raw=True)
read_operation_location = read_response.headers["Operation-Location"]
operation_id = read_operation_location.split("/")[-1]
while True:
    read_result = computervision_client.get_read_result(operation_id)
    if read_result.status not in ['notStarted', 'running']:
        break
    time.sleep(1)
if read_result.status == OperationStatusCodes.succeeded:
    for text_result in read_result.analyze_result.read_results:
       for line in text_result.lines:
           print(line.text)
           print(line.bounding_box)
print()    

运行结果:可以看到识别到的文本

3.2 本地图像识别

用我自己手写的文字来试下,有标点符号,甚至还特别写了一个看不清的哎呀,让它识别一下

#OCR文本识别-本地
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
import time
import os
computervision_client = ComputerVisionClient(You endpoint, 
                                             CognitiveServicesCredentials( Your key))
local_image_path = os.path.join("C:\\Users\\Uniigym3\\AppData\\Roaming\\Python\\Python38\\Scripts\\images", "ocrTest2.jpg")
local_image = open(local_image_path, "rb")
read_response  = computervision_client.read_in_stream(local_image,  raw=True)
read_operation_location = read_response.headers["Operation-Location"]
operation_id = read_operation_location.split("/")[-1]
while True:
    read_result = computervision_client.get_read_result(operation_id)
    if read_result.status.lower () not in ['notstarted', 'running']:
        break
    print ('Waiting for result...')
print(read_result)    
if read_result.status == OperationStatusCodes.succeeded:
    for text_result in read_result.analyze_result.read_results:
       for line in text_result.lines:
           print(line.text)
           print(line.bounding_box)
print()    

运行结果:太感动了哈,它竟然识别出来了,甚至perfect的.都识别出来了 ,很有意思

 我尝试把照片倒过来,然后就识别不到那个不清楚的字了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/155987.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Vue数据绑定

在我们Vue当中有两种数据绑定的方法 1.单向绑定 2.双向绑定 让我为大家介绍一下吧&#xff01; 1、单向绑定(v-bind) 数据只能从data流向页面 举个例子&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"…

图论| 827. 最大人工岛 127. 单词接龙

827. 最大人工岛 题目&#xff1a;给你一个大小为 n x n 二进制矩阵 grid 。最多 只能将一格 0 变成 1 。返回执行此操作后&#xff0c;grid 中最大的岛屿面积是多少&#xff1f; 岛屿 由一组上、下、左、右四个方向相连的 1 形成。 题目链接&#xff1a;[827. 最大人工岛](ht…

佳易王麻将馆计时收费系统怎么安装,麻将馆的灯控什么原理?

佳易王麻将馆计时收费系统怎么安装&#xff0c;麻将馆的灯控什么原理&#xff1f; 佳易王计时计费软件只需将压缩包文件解压即可使用&#xff0c;灯控的原理是&#xff1a;软件在点击开始计时的时候&#xff0c;软件向灯控器发送开灯信号&#xff0c;相应的灯打开&#xff0c;…

【面试】测试/测开(未完成)

1. 黑盒测试方法 黑盒测试&#xff1a;关注的是软件功能的实现&#xff0c;关注功能实现是否满足需求&#xff0c;测试对象是基于需求规格说明书。 1&#xff09;等价类&#xff1a;有效等价类、无效等价类 2&#xff09;边界值 3&#xff09;因果图&#xff1a;不同的原因对应…

C/C+=内存管理

C/C内存管理以及动态内存的申请_c动态内存的申请与释放_Demo Test的博客-CSDN博客 问题是&#xff0c;这个0x0804 8000 到0xC 0000 0000之间&#xff0c;不止3GB&#xff0c;应该有47GB&#xff0c;该怎么解释呢&#xff1f;

【图像分类】【深度学习】【Pytorch版本】ResNet模型算法详解

【图像分类】【深度学习】【Pytorch版本】 ResNet模型算法详解 文章目录 【图像分类】【深度学习】【Pytorch版本】 ResNet模型算法详解前言ResNet讲解Deep residual learning framework(深度残差学习框架)ResNet残差结构ResNet模型结构 ResNet Pytorch代码完整代码总结 前言 …

深入探讨TensorFlow:张量与矩阵

在机器学习和深度学习领域中&#xff0c;TensorFlow作为一款强大且受欢迎的开源机器学习框架&#xff0c;为研究人员和开发者提供了丰富的工具和资源。在TensorFlow中&#xff0c;张量&#xff08;tensor&#xff09;和矩阵&#xff08;matrix&#xff09;是核心概念&#xff0…

Odoo 15开发手册第七章 记录集 - 使用模型数据

在前面的章节中&#xff0c;我们概览了模型创建以及如何向模型加载数据。现在我们已有数据模型和相关数据&#xff0c;是时候学习如何编程与其进行交互了。 业务应用需要业务逻辑来计算数据、执行验证或自动化操作。Odoo框架API为开发者提供了工具用于实现这种业务逻辑。大多数…

(二)什么是Vite——Vite 和 Webpack 区别(冷启动)

vite分享ppt&#xff0c;感兴趣的可以下载&#xff1a; ​​​​​​​Vite分享、原理介绍ppt 什么是vite系列目录&#xff1a; &#xff08;一&#xff09;什么是Vite——vite介绍与使用-CSDN博客 &#xff08;二&#xff09;什么是Vite——Vite 和 Webpack 区别&#xff0…

2018年五一杯数学建模C题江苏省本科教育质量综合评价解题全过程文档及程序

2019年五一杯数学建模 C题 江苏省本科教育质量综合评价 原题再现 随着中国的改革开放&#xff0c;国家的综合实力不断增强&#xff0c;中国高等教育发展整体已进入世界中上水平。作为一个教育大省&#xff0c;江苏省的本科教育发展在全国名列前茅&#xff0c;而江苏省13个地级…

【PB续命05】WinHttp.WinHttpRequest的介绍与使用

0 WinHttp.WinHttpRequest简介 winhttp.winhttprequest是Windows操作系统中的一个API函数&#xff0c;用于创建和发送HTTP请求。它可以用于从Web服务器获取数据&#xff0c;或将数据发送到Web服务器。该函数提供了许多选项&#xff0c;例如设置请求头、设置代理服务器、设置超…

花 200 元测试 1300 个实时数据同步任务

背景 对于将数据作为重要生产资料的公司来说&#xff0c;超大规模的数据迁移同步系统( 1k、5k、10k 条同步任务)是刚需。 本文以此为出发点&#xff0c;介绍近期 CloudCanal 所做的一个容量测试&#xff1a;在单个 CloudCanal 集群上创建 1300 实时任务&#xff0c;验证系统是…

2023年中国骨质疏松治疗仪发展趋势分析:小型且智能将成为产品优化方向[图]

骨质疏松治疗仪利用磁场镇静止痛、消肿消炎的治疗作用迅速缓解患者腰背疼痛等骨质疏松临床症状。同时利用磁场的磁-电效应产生的感生电势和感生电流&#xff0c;改善骨的代谢和骨重建&#xff0c;通过抑制破骨细胞、促进成骨细胞的活性来阻止骨量丢失、提高骨密度。 骨质疏松治…

【软件推荐】我的常用Windows软件

文章目录 前言Colors Lite&#xff08;颜色吸取&#xff09;Everything&#xff08;文件搜索&#xff09;知云文献翻译Directory Opus&#xff08;文件管理器&#xff09;Snipaste&#xff08;截图&#xff09;AxMath&#xff08;公式编辑器&#xff09;Deskpin&#xff08;窗口…

【Android】导入三方jar包/系统的framework.jar

1.Android.mk导包 1).jar包位置 与res和src同一级的libs中(没有就新建) 2).Android.mk文件 LOCAL_STATIC_ANDROID_LIBRARIES&#xff1a;android静态库&#xff0c;经常用于一些support的导包 LOCAL_JAVA_LIBRARIES&#xff1a;依赖的java库&#xff0c;一般为系统的jar…

Linux常用命令——bzcmp命令

在线Linux命令查询工具 bzcmp 比较两个压缩包中的文件 补充说明 bzcmp命令主要功能是在不真正解压缩.bz2压缩包的情况下&#xff0c;比较两个压缩包中的文件&#xff0c;省去了解压缩后在调用cmp命令的过程。 语法 bzcmp(参数)参数 文件1&#xff1a;指定要比较的第一个…

UE基础篇十:材质

导语: 视频文档在文末 虚幻引擎默认是延迟渲染(延迟渲染是通过先算出需要着色的像素,然后再迭代灯光,从而减少大量无效的灯光计算,来达到优化的目的) 一、基础知识 1.1 贴图分辨率尺寸 2的幂次方,长宽随意组合 非2的幂次方,不能设置MipMaps(引擎会生成多张分辨率更…

任务栏上的超萌小猫,实时显示CPU占用率,有趣.Net开源工具

推荐一个非常有趣的.Net开源小工具&#xff0c;它可以在电脑任务栏显示一只奔跑的小猫&#xff0c;实时显示CPU使用率&#xff01; 01 项目简介 一款基于.NET 6.0运行环境的开源小工具&#xff0c;通过它&#xff0c;用户可以直观地查看CPU的使用情况&#xff0c;它会根据 CP…

程序员导航站

探路者 hello.alluniverse.vip 开发者导航 - Pro Developer网站导航 探路者是一款极简导航工具&#xff0c;致力于收录的每个站点都有其独特的作用。同时支持自定义导航&#xff0c;让用户快速实现个性化的导航站点。 特性概述 免费ChatGPT 装机必备 开发工具 Git精选项目 …

云计算(Docker)

Docker简介 Docker 是一个开源的应用容器引擎&#xff0c;基于 Go 语言&#xff0c;并遵从 Apache2.0 协议开源。它可以让开发者打包应用以及依赖包到一个轻量级、可移植的容器中&#xff0c;然后发布到任何流行的 Linux 机器上&#xff0c;也可以实现虚拟化。Docker 可用于开发…
最新文章