同一张图片在同一个roboflow在线模型上检测,通过api调用模型预测和roboflow widget的预测相差甚远

尝试过:1将图像转换为 base64 编码的字符串,然后将其 POST 请求的数据发送。2##### The same image is passed to the same model detection (the path is different, one is to the model framework on roboflow to submit directly, one is through the model api on roboflow to submit), the returned data is not the same: the api returns the same confidence front labels, the accuracy is very low. And the confidence level of all the labels returned by the api is low, just below 0.2. Here is the data returned via roboflow’s api:: DEBUG:root:Processing file: 84.jpg DEBUG:root:Starting to process image file. DEBUG:root: calling Inference API for inference: temp\84.jpg DEBUG:root: inference result: [MultiLabelClassificationInferenceResponse(visualization=None, inference_id=None, frame_id=None, time=None, image=InferenceResponseImage(width=640, height=640), predictions={‘caries’: MultiLabelClassificationPrediction(confidence=0.16454234719276428, class_id=0), ‘Fractured tooth’: MultiLabelClassificationPrediction(confidence=0.07140594720840454, class_id=1), : The following data was submitted and returned on the roboflowsite and returned: { “prediction”: { “mismatch”: { “confidence”: 0.763, “class_id”: 8 } Here’s the AI answer from roboflow for reference: It seems that when working with the same image and model using the Roboflow API and the Roboflow web interface, you are experiencing different results.This could be due to a number of factors, including different confidence thresholds or other settings used in the two methods.In the Roboflow platform, the JSON values returned by the API and widgets are the output you receive when you perform inference using a deployed model.The JSON output for Multi-Label Classification (MLC) consists of the Prediction, which is a JSON set containing the confidence score for each class present in the dataset during model training, and the Confidence, which is the confidence value for the prediction.Cinco de Mayo, Beer and Taco datasets with multi-label classification blog post shows examples of JSON output.If you are using the Python SDK to run inference on the model, you can specify confidence and overlap parameters in the function, as shown in the How to Deploy YOLOv8 Object Detection Models to AWS EC2model.predict() guide shows.

I need the help so much——thank you for your effort. The predictions obtained through the api——different images have the same label, and the confidence of all 10 label labels is below 0.2. It is normal to get predictions directly from images on roboflow.
My py files also have preprocessing codes, and the model and version used are only one.
The following is my app code: import os import requests from flask import Flask, request, jsonify, render_template import inference from dotenv import load_dotenv import logging from PIL import Image import numpy as np import cv2 # Load environment variables load_dotenv() app = Flask(name) # Configure logging logging.basicConfig(level=logging.DEBUG) # Get the API key and model ID API_KEY = os.getenv(“ROBOFLOW_API_KEY”, “WarG5c2S5LChi11111111”) # Make sure to replace with your actual API key MODEL_ID = "dai-4bmc3I need the help so much——thank you for your effort. The predictions obtained through the api——different images have the same label, and the confidence of all 10 label labels is below 0.2. It is normal to get predictions directly from images on roboflow. My py files also have preprocessing codes, and the model and version used are only one. The following is my app code: import os import requests from flask import Flask, request, jsonify, render_template import inference from dotenv import load_dotenv import logging from PIL import Image import numpy as np import cv2 # Load environment variables load_dotenv() app = Flask(name) # Configure logging logging.basicConfig(level=logging.DEBUG)

Get the API key and model ID API_KEY = os.getenv(“ROBOFLOW_API_KEY”, “WarG5c2S5LChi11111111”) # Make sure to replace with your actual API key MODEL_ID = “dai-4bmc3” # 项目名称/版本号

初始化模型

try:
model = inference.get_model(MODEL_ID)
model.api_key = API_KEY # 设置 API Key
logging.debug(f"已初始化模型:{MODEL_ID}“)
except Exception as e:
logging.error(f"初始化模型时出错: {e}”)

def preprocess_image(image_path):
# 读取图像
image = cv2.imread(image_path)

# 检查图像是否成功读取
if image is None:
    raise ValueError(f"无法读取图像: {image_path}")

# 将图像从BGR转换为RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# 调整图像大小为640x640
image = cv2.resize(image, (640, 640))

# 归一化像素值到[0, 1]范围
image = image.astype(np.float32) / 255.0

# 返回3维数组,不添加批次维度
return image  # 形状为(640, 640, 3)

def process_image(file):
“”"
处理上传的图像文件,并调用 Roboflow API 进行推理。
“”"
logging.debug(“开始处理图像文件。”)
# 保存临时文件
temp_dir = “temp”
os.makedirs(temp_dir, exist_ok=True)
file_path = os.path.join(temp_dir, file.filename)
file.save(file_path)
logging.debug(f"调用 Inference API 进行推理: {file_path}")

try:
    # 预处理图像
    preprocessed_image = preprocess_image(file_path)

    # 调用模型进行推理
    result = model.infer(image=preprocessed_image)  # 直接传递3维数组
    logging.debug(f"推理结果: {result}")

    # 检查结果的类型
    if isinstance(result, list) and len(result) > 0:
        inference_response = result[0]
        predictions = inference_response.predictions
    else:
        predictions = result.predictions if hasattr(result, 'predictions') else {}

    # 将预测结果转换为可序列化的格式
    serialized_predictions = {}
    for class_name, prediction in predictions.items():
        serialized_predictions[class_name] = {
            "confidence": prediction.confidence,
            "class_id": prediction.class_id
        }

    response = {
        "predictions": serialized_predictions,
        "image": None
    }
    logging.debug(f"返回结果: {response}")  # 打印返回结果
    return response
except Exception as e:
    logging.error(f"调用 Inference API 时出错: {e}")
    return {"error": str(e)}
finally:
    # 清理临时文件
    if 'file_path' in locals() and os.path.exists(file_path):
        os.remove(file_path)
        logging.debug(f"已删除临时文件: {file_path}")

@app.route(‘/upload’, methods=[‘POST’])
def upload_file():
“”"
处理文件上传请求。
“”"
logging.debug(“收到上传请求。”)
if ‘file’ not in request.files:
logging.warning(“上传请求中缺少文件部分。”)
return jsonify({“error”: “没有文件部分”}), 400

file = request.files['file']

if file.filename == '':
    logging.warning("上传请求中没有选择文件。")
    return jsonify({"error": "没有选择文件"}), 400

if file:
    logging.debug(f"处理文件: {file.filename}")
    result = process_image(file)
    return jsonify(result)

logging.error("上传请求中发生未知错误。")
return jsonify({"error": "未知错误"}), 500

@app.route(‘/’)
def index():
“”"
简单的首页路由,提供上传文件的表单。
“”"
return render_template(‘index.html’)

if name == ‘main’:
# 以调试模式运行应用,方便开发过程中调试
app.run(debug=True)