如何在R Studio中调用Azure Vision API获取与演示页一致的输出?
解决RStudio调用Azure视觉OCR API匹配演示页输出问题
你的代码存在的核心问题
- 本地图片传递方式错误:API的
url参数仅支持公网可访问的图片链接,本地图片需要以二进制形式上传,而非填写本地路径。 - 异步API流程未处理:Azure Read API是异步调用,提交请求后不会直接返回结果,需要从响应头的
operation-location获取任务地址,轮询等待任务完成后再获取结果。
修正后的完整代码示例
library(httr) library(jsonlite) # 配置API信息 api_endpoint <- "https://XXXXXXX.cognitiveservices.azure.com/vision/v3.2/read/analyze" api_key <- "XXXXX" local_image_path <- "C:/XXX/image.jpg" # 第一步:提交图片分析请求(本地图片以二进制上传) submit_response <- POST( url = api_endpoint, add_headers( `Ocp-Apim-Subscription-Key` = api_key, `Content-Type` = "application/octet-stream" ), body = upload_file(local_image_path) ) # 检查请求是否成功提交 if (status_code(submit_response) != 202) { stop("提交请求失败,错误信息:", content(submit_response)$error$message) } # 获取任务查询地址 operation_url <- headers(submit_response)$`operation-location` # 第二步:轮询获取分析结果 result_response <- NULL while (is.null(result_response) || content(result_response)$status == "running") { Sys.sleep(1) # 每隔1秒查询一次 result_response <- GET( url = operation_url, add_headers(`Ocp-Apim-Subscription-Key` = api_key) ) } # 第三步:解析并整理结果(匹配演示页的文本输出格式) analysis_result <- content(result_response) if (analysis_result$status == "succeeded") { # 提取所有识别到的文本行 extracted_text <- sapply(analysis_result$analyzeResult$readResults[[1]]$lines, function(line) line$text) # 输出与演示页一致的纯文本(按换行分隔) cat(paste(extracted_text, collapse = "\n")) } else { stop("分析任务失败:", analysis_result$error$message) }
匹配AzureVision::read_text()与演示页输出的调整建议
如果使用AzureVision::read_text()输出接近但不一致,可能是默认参数差异导致:
- 演示页可能默认启用了手写文本识别,可以在调用时指定
model = "latest"或显式设置handwriting = TRUE - 指定与演示页一致的语言参数,比如
language = "zh-Hans"(如果是中文文本) - 示例:
library(AzureVision) # 初始化服务 vision_service <- vision_endpoint("https://XXXXXXX.cognitiveservices.azure.com/", api_key) # 调用时设置匹配演示页的参数 result <- read_text(vision_service, local_image_path, handwriting = TRUE, language = "zh-Hans") # 提取纯文本输出 cat(paste(result$content, collapse = "\n"))
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

