当前位置: 首页 > news >正文

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 AzureKeyCredentialdef authenticate_client():ta_credential= AzureKeyCredential(key)text_analytics_client=TextAnalyticsClient(endpoint=endpoint,credential=ta_credential)return text_analytics_clientclient=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:fengjava程你好想学多的知识

换成英文 

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 osos.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 osos.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 sdkservice_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 timecomputervision_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']:breaktime.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']:breakprint ('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的.都识别出来了 ,很有意思

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

相关文章:

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

1.语言检测 安装包: # 语言检测 %pip install azure-ai-textanalytics5.2.0 需要用到密钥和资源的终结点,所以去Azure上创建资源,我这个是创建好的了然后点击密钥和终结者去拿到key和终结点 两个密钥选择哪个都行 语言检测代码示例&#…...

QDateEdit开发详解

文章目录 一、创建 `QDateEdit` 对象二、设置日期范围三、设置当前日期四、获取选择的日期五、显示日历弹出窗口六、信号与槽七、格式化日期显示1. `QDateTime` 类2. 日期时间格式化字符串3. 自定义格式化字符串4. 本地化日期格式5. `QDate` 和 `QTime` 的格式化6. 时间戳转日期…...

3.6 Windows驱动开发:内核进程汇编与反汇编

在笔者上一篇文章《内核MDL读写进程内存》简单介绍了如何通过MDL映射的方式实现进程读写操作,本章将通过如上案例实现远程进程反汇编功能,此类功能也是ARK工具中最常见的功能之一,通常此类功能的实现分为两部分,内核部分只负责读写…...

zsh和ohmyzsh安装指南+插件推荐

文章目录 1. 安装指南2. 插件配置指南3. 参考信息 1. 安装指南 1. 安装 zsh sudo apt install zsh2. 安装 Oh My Zsh 国内访问GitHub sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"这将安装 Oh My Zsh 和所…...

VS中修改解决方案名称和项目名称

如何修改visual studio2019中的项目名 - 知乎 (zhihu.com) 查了很多,还是这个可行。虽然文中说不是最简单的,但在所查找资料中是可行且最简单的。 要点主要是: 1、比如我们复制一个解决方案,最好是带代码哈,也就是添…...

iOS UITableView获取到的contentSize不正确

在开发中遇到一个需求,就是将一个tableView的contentsize设置成该 tableView的frame的size,但是 经过调试,发现获取到的contentsize不争确,后来发现是 没有设置一个属性 if (available(iOS 15.0, *)) {_tableView.sectionHeaderTopPadding …...

C++二分查找算法:查找和最小的 K 对数字

相关专题 二分查找相关题目 题目 给定两个以 非递减顺序排列 的整数数组 nums1 和 nums2 , 以及一个整数 k 。 定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2 。 请找到和最小的 k 个数对 (u1,v1), (u2,v2) … (uk,vk) 。 示例 1:…...

开源WIFI继电器之方案介绍

一、实物 1、外观 2、电路板 二、功能说明 输出一路继电器常开信号,最大负载电流10A输入一路开关量检测联网方式2.4G Wi-Fi通信协议MQTT配网方式AIrkiss,SmartConfig设备管理本地Web后台管理,可配置MQTT参数供电AC220V其它一个功能按键&…...

html使用天地图写一个地图列表

一、效果图&#xff1a; 点击左侧地址列表&#xff0c;右侧地图跟着改变。 二、代码实现&#xff1a; 一进入页面时&#xff0c;通过body调用onLoad"onLoad()"函数&#xff0c;确保地图正常显示。 <body onLoad"onLoad()"><!--左侧代码-->…...

C++ Qt 学习(九):模型视图代理

1. Qt 模型视图代理 Qt 模型视图代理&#xff0c;也可以称为 MVD 模式 模型(model)、视图(view)、代理(delegate)主要用来显示编辑数据 1.1 模型 模型 (Model) 是视图与原始数据之间的接口 原始数据可以是&#xff1a;数据库的一个数据表、内存中的一个 StringList&#xff…...

wpf devexpress 自定义统计

总计统计和分组统计包含预定义总计函数。这些函数允许你计算如下&#xff1a; 数据列的数量&#xff08;Count&#xff09; 最大和最小值(Max和Min) 总计和平均值&#xff08;Sum和Average&#xff09; 处理GridControl.CustomSummary 事件或者使用 GridControl.CustomSumm…...

【Flink】Flink任务缺失Jobmanager日志的问题排查

Flink任务缺失Jobmanager日志的问题排查 问题不是大问题&#xff0c;不是什么代码级别的高深问题&#xff0c;也没有影响任务运行&#xff0c;纯粹因为人员粗心导致&#xff0c;记录一下排查的过程。 问题描述 一个生产环境的奇怪问题&#xff0c;环境是flink1.15.0 on yarn…...

教程:使用 Keras 优化神经网络

一、介绍 在 我 之前的文章中&#xff0c;我讨论了使用 TensorFlow 实现神经网络。继续有关神经网络库的系列文章&#xff0c;我决定重点介绍 Keras——据说是迄今为止最好的深度学习库。 我 从事深度学习已经有一段时间了&#xff0c;据我所知&#xff0c;处理…...

什么是PWA(Progressive Web App)?它有哪些特点和优势?

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…...

深入理解MongoDB的CRUD操作

MongoDB&#xff0c;一个广受欢迎的NoSQL数据库&#xff0c;以其灵活的文档模型、强大的查询能力和易于扩展的特性而著称。对于初学者和经验丰富的开发人员来说&#xff0c;熟练掌握MongoDB的增删改查&#xff08;CRUD&#xff09;操作是至关重要的。本博客将深入探讨如何在Mon…...

使用量子玻尔兹曼机推进机器学习:新范式

一、说明 量子玻尔兹曼机&#xff08;QBM&#xff09;是量子物理学和机器学习的前沿融合。通过利用叠加和纠缠等量子特性的力量&#xff0c;QBM 可以同时探索多个解决方案&#xff0c;使其异常擅长解决复杂问题。它使用量子位&#xff08;量子计算的构建模块&#xff09;以传统…...

优化|优化求解器自动调参

原文信息&#xff1a;MindOpt Tuner: Boost the Performance of Numerical Software by Automatic Parameter Tuning 作者&#xff1a;王孟昌 &#xff08;达摩院决策智能实验室MindOpt团队成员&#xff09; 一个算法开发者&#xff0c;可能会幻想进入这样的境界&#xff1a;算…...

vite vue3配置eslint和prettier以及sass

准备 教程 安装eslint 官网 vue-eslint ts-eslint 安装eslint yarn add eslint -D生成配置文件 npx eslint --init安装其他插件 yarn add -D eslint-plugin-import eslint-plugin-vue eslint-plugin-node eslint-plugin-prettier eslint-config-prettier eslint-plugin…...

C语言第入门——第十六课

目录 一、分治策略与递归 二、递归 1.求解n的阶乘 2.输入整数、倒序输出 3.输入整数、正序输出 4.计算第n位Fibonacci数列 ​编辑5.无序整数数组打印 6.找到对应数组下标 一、分治策略与递归 在我们遇到大问题的时候&#xff0c;我们的正确做法是将它分解成小问题&a…...

IntelliJ IDEA 快捷键 Windows 版本

前言&#xff1a;常用快捷键 IntelliJ IDEA编辑器大受欢迎的原因之一是它的智能提示和丰富的快捷键&#xff0c;在日常开发中熟练的使用快捷键会大大提升开发的效率&#xff0c;本篇文章就笔者日常开发中的总结&#xff0c;把常用的、好用的快捷键做一个列表&#xff0c;方便…...

HTML 语义化

目录 HTML 语义化HTML5 新特性HTML 语义化的好处语义化标签的使用场景最佳实践 HTML 语义化 HTML5 新特性 标准答案&#xff1a; 语义化标签&#xff1a; <header>&#xff1a;页头<nav>&#xff1a;导航<main>&#xff1a;主要内容<article>&#x…...

内存分配函数malloc kmalloc vmalloc

内存分配函数malloc kmalloc vmalloc malloc实现步骤: 1)请求大小调整:首先,malloc 需要调整用户请求的大小,以适应内部数据结构(例如,可能需要存储额外的元数据)。通常,这包括对齐调整,确保分配的内存地址满足特定硬件要求(如对齐到8字节或16字节边界)。 2)空闲…...

C++:std::is_convertible

C++标志库中提供is_convertible,可以测试一种类型是否可以转换为另一只类型: template <class From, class To> struct is_convertible; 使用举例: #include <iostream> #include <string>using namespace std;struct A { }; struct B : A { };int main…...

【网络安全产品大调研系列】2. 体验漏洞扫描

前言 2023 年漏洞扫描服务市场规模预计为 3.06&#xff08;十亿美元&#xff09;。漏洞扫描服务市场行业预计将从 2024 年的 3.48&#xff08;十亿美元&#xff09;增长到 2032 年的 9.54&#xff08;十亿美元&#xff09;。预测期内漏洞扫描服务市场 CAGR&#xff08;增长率&…...

python如何将word的doc另存为docx

将 DOCX 文件另存为 DOCX 格式&#xff08;Python 实现&#xff09; 在 Python 中&#xff0c;你可以使用 python-docx 库来操作 Word 文档。不过需要注意的是&#xff0c;.doc 是旧的 Word 格式&#xff0c;而 .docx 是新的基于 XML 的格式。python-docx 只能处理 .docx 格式…...

DBAPI如何优雅的获取单条数据

API如何优雅的获取单条数据 案例一 对于查询类API&#xff0c;查询的是单条数据&#xff0c;比如根据主键ID查询用户信息&#xff0c;sql如下&#xff1a; select id, name, age from user where id #{id}API默认返回的数据格式是多条的&#xff0c;如下&#xff1a; {&qu…...

《基于Apache Flink的流处理》笔记

思维导图 1-3 章 4-7章 8-11 章 参考资料 源码&#xff1a; https://github.com/streaming-with-flink 博客 https://flink.apache.org/bloghttps://www.ververica.com/blog 聚会及会议 https://flink-forward.orghttps://www.meetup.com/topics/apache-flink https://n…...

QT3D学习笔记——圆台、圆锥

类名作用Qt3DWindow3D渲染窗口容器QEntity场景中的实体&#xff08;对象或容器&#xff09;QCamera控制观察视角QPointLight点光源QConeMesh圆锥几何网格QTransform控制实体的位置/旋转/缩放QPhongMaterialPhong光照材质&#xff08;定义颜色、反光等&#xff09;QFirstPersonC…...

从“安全密码”到测试体系:Gitee Test 赋能关键领域软件质量保障

关键领域软件测试的"安全密码"&#xff1a;Gitee Test如何破解行业痛点 在数字化浪潮席卷全球的今天&#xff0c;软件系统已成为国家关键领域的"神经中枢"。从国防军工到能源电力&#xff0c;从金融交易到交通管控&#xff0c;这些关乎国计民生的关键领域…...

五子棋测试用例

一.项目背景 1.1 项目简介 传统棋类文化的推广 五子棋是一种古老的棋类游戏&#xff0c;有着深厚的文化底蕴。通过将五子棋制作成网页游戏&#xff0c;可以让更多的人了解和接触到这一传统棋类文化。无论是国内还是国外的玩家&#xff0c;都可以通过网页五子棋感受到东方棋类…...