You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问Azure Image Analysis 4.0 API?遇404资源未找到错误求助

Azure Image Analysis 4.0 API 404资源未找到问题排查与解决

问题背景

部署在美国东部(USA EAST)区域的Azure Image Analysis 4.0资源,通过Python代码调用REST API时持续返回404 "Resource not found"错误。

实现代码

import os
import requests
import pyautogui
from PIL import Image
from io import BytesIO
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials

# Azure Configuration
SUBSCRIPTION_KEY = "..."
ENDPOINT = "..."

# OpenAI Configuration
OPENAI_KEY = "..."

def take_screenshot():
    screenshot = pyautogui.screenshot()
    output = BytesIO()
    screenshot.save(output, format="PNG")
    output.seek(0)  # Rewind the stream back to the beginning before reading from it
    return output

def analyze_image(image_stream):
    headers = {
        'Content-Type': 'application/octet-stream',
        'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY,
    }
    params = {
        'visualFeatures': 'Objects,Tags,Description,Faces,ImageType,Color,Adult',
        'language': 'en',
    }
    response = requests.post(ENDPOINT + 'vision/v4.0/analyze', headers=headers, params=params, data=image_stream)
    print(f"Status code: {response.status_code}")
    print(f"Response text: {response.text}")
    response.raise_for_status()
    return response.json()

def query_openai(azure_result):
    headers = {
        'Authorization': f'Bearer {OPENAI_KEY}',
        'Content-Type': 'application/json',
    }
    
    # Format the Azure result into a string
    result_string = "Description: {}. Tags: {}. Objects: {}. Adult content: {}. Racy content: {}.".format(
        azure_result['description']['captions'][0]['text'] if azure_result['description']['captions'] else "None",
        ', '.join([tag['name'] for tag in azure_result['tags']]),
        ', '.join([obj['objectProperty'] for obj in azure_result['objects']]) if 'objects' in azure_result and azure_result['objects'] else "None",
        azure_result['adult']['isAdultContent'],
        azure_result['adult']['isRacyContent']
    )

    print(f"Azure details sent to OpenAI: {result_string}")  # Print the Azure details

    data = {
        'model': 'gpt-4',
        'messages': [
            {"role": "system", "content": "Translate the following Azure Image Analysis result to a boolean value."},
            {"role": "user", "content": f"{result_string}. Does the image contain an apple?"}
        ]
    }
    
    response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=data)
    return response.json()['choices'][0]['message']['content'].strip().lower() == 'true'

if __name__ == "__main__":
    image_data = take_screenshot()
    azure_result = analyze_image(image_data)
    is_apple_present = query_openai(azure_result)
    print('Does the screen have an apple on it?', is_apple_present)

错误响应

Status code: 404
Response text: {"error":{"code":"404","message": "Resource not found"}}
Traceback (most recent call last):
  File "C:\Users\...\Desktop\ScreenAnalysisApp\app.py", line 69, in <module>
    azure_result = analyze_image(image_data)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\Desktop\ScreenAnalysisApp\app.py", line 36, in analyze_image
    response.raise_for_status()
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Resource Not Found for url: https://purefocus.cognitiveservices.azure.com/vision/v4.0/analyze?visualFeatures=Objects%2CTags%2CDescription%2CFaces%2CImageType%2CColor%2CAdult&language=en

排查与解决

核心问题:API端点路径与参数不匹配

Azure Image Analysis 4.0使用了全新的API端点和参数格式,旧的/vision/v4.0/analyze路径属于Computer Vision v3.x版本,不适用于4.0版本。

具体修正步骤

  1. 更换API端点路径
    将代码中的ENDPOINT + 'vision/v4.0/analyze'替换为ENDPOINT + 'computervision/imageanalysis:analyze',并添加api-version参数(推荐使用2023-02-01-preview或更新的GA版本)。

  2. 调整请求参数
    4.0版本用features替代了旧的visualFeatures参数,且feature名称为小写格式,比如caption代替Description、objects代替Objects。

  3. 适配返回的JSON结构
    4.0版本的响应结构与旧版本不同,比如描述信息在captionResult字段下,标签在tagsResult.values下,需要同步调整后续处理逻辑。

修正后的关键代码片段

修正后的analyze_image函数

def analyze_image(image_stream):
    headers = {
        'Content-Type': 'application/octet-stream',
        'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY,
    }
    params = {
        'features': 'objects,tags,caption,faces,imageType,color,adult',
        'language': 'en',
        'api-version': '2023-02-01-preview'
    }
    # 使用4.0版本的正确路径
    response = requests.post(ENDPOINT + 'computervision/imageanalysis:analyze', headers=headers, params=params, data=image_stream)
    print(f"Status code: {response.status_code}")
    print(f"Response text: {response.text}")
    response.raise_for_status()
    return response.json()

修正后的query_openai函数中的结果格式化部分

# 适配4.0版本的响应结构
result_string = "Description: {}. Tags: {}. Objects: {}. Adult content: {}. Racy content: {}.".format(
    azure_result['captionResult']['text'] if azure_result['captionResult']['text'] else "None",
    ', '.join([tag['name'] for tag in azure_result['tagsResult']['values']]),
    ', '.join([obj['name'] for obj in azure_result['objectsResult']['values']]) if 'objectsResult' in azure_result and azure_result['objectsResult']['values'] else "None",
    azure_result['adultResult']['isAdultContent'],
    azure_result['adultResult']['isRacyContent']
)

额外验证点

  • 确认Azure资源是Computer Vision(单服务或多服务),且处于正常运行状态。
  • 验证ENDPOINT配置正确,未遗漏末尾的斜杠(如果你的ENDPOINT没有斜杠,拼接时需要加上,比如ENDPOINT.rstrip('/') + '/computervision/...')。

内容的提问来源于stack exchange,提问作者Troy Robinson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:16:00