如何将下面静态的url修改成动态的url(url是后端将数据库的内容与我的接口做链接,数据库给什么url我的接口就自动变换成什么url),同时要将处理完的代码返还给后端。
import os
import random
import time
import cv2
import onnxruntime
from opt_einsum.backends import torch
from tool import *
from flask import Flask, request, jsonify
import numpy as np
from urllib.request import urlopen
app = Flask(__name__)
def onnx_load(w):
cuda = torch.cuda.is_available()
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']
session = onnxruntime.InferenceSession(w, providers=providers)
output_names = [x.name for x in session.get_outputs()]
return session, output_names
def calculate_height(bbox):
height = bbox[3] - bbox[1]
return height
def annotate_image(image, boxes, labels):
for box, label in zip(boxes, labels):
x1, y1, x2, y2 = [int(coord) for coord in box]
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return image
def url_to_image(url):
try:
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
except Exception as e:
print(f"从URL {url} 获取图像时出错:{e}")
return None
@app.route('/process_image', methods=['POST'])
def process_image():
data = request.get_json()
w = data['model_path']
image_url = 'https://hoire.oss-cn-shenzhen.aliyuncs.com/313254_638567497450816069.jpg'
imgsz = [640, 640]
session, output_names = onnx_load(w)
device = torch.device('cuda:0')
im0 = url_to_image(image_url)
if im0 is None:
return jsonify({"error": f"Unable to load image from URL: {image_url}"}), 400
im, org_data = data_process_cv2(im0, imgsz)
start_time = time.time()
y = session.run(output_names, {session.get_inputs()[0].name: im})
pred = torch.from_numpy(y[0]).to(device)
pred = non_max_suppression(pred, conf_thres=0.25, iou_thres=0.45, max_det=1000)
spend_time_ms = (time.time() - start_time) * 1000
res_img = post_process_yolov5(pred[0], org_data)
boxes = []
labels = []
person_heights = []
bicycle_heights = []
if pred[0] is not None and isinstance(pred[0], torch.Tensor):
for det in pred[0]:
if det is not None and len(det) >= 4:
box = det[:4].tolist()
boxes.append(box)
height = calculate_height(box)
class_id = int(det[5].item()) if len(det) > 5 else -1
label = 'person' if class_id == 1 else 'bicycle' if class_id == 0 else 'unknown'
labels.append(f'{label}: {height:.2f}')
if label == 'person':
person_heights.append(height)
elif label == 'bicycle':
bicycle_heights.append(height)
else:
return jsonify({"error": "pred[0] is either None or not a Tensor."}), 400
res_img = annotate_image(res_img, boxes, labels)
save_dir = 'D:/sansheng/zg/jiekou/image/train'
os.makedirs(save_dir, exist_ok=True)
res_img_name = f"res_{os.path.basename(image_url)}"
res_img_path = os.path.join(save_dir, res_img_name)
cv2.imwrite(res_img_path, res_img)
response = {
"spend_time_ms": spend_time_ms,
"annotated_image_path": res_img_path,
"average_person_height": sum(person_heights) / len(person_heights) if person_heights else None,
"average_bicycle_height": sum(bicycle_heights) / len(bicycle_heights) if bicycle_heights else None,
}
return jsonify(response), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
import requests
# 定义接口的URL
url = 'http://192.168.0.75:5000/process_image'
data = {
'model_path': 'best.onnx', # 指定要使用的ONNX模型文件路径
# 'image_url': 'https://hoire.oss-cn-shenzhen.aliyuncs.com/313254_638567497450816069.jpg' # 要处理的图像文件路径
}
# 发送POST请求到接口,并传递数据
response = requests.post(url, json=data)
# 检查请求是否成功
if response.status_code == 200:
result = response.json()
print(f"输出处理时间: {result['spend_time_ms']} ms")
print(f"输出保存的标注图像路径: {result['annotated_image_path']}")
if result['average_person_height']:
print(f"玉米的平均高度: {result['average_person_height']:.2f}")
if result['average_bicycle_height']:
print(f"竹竿的平均高度: {result['average_bicycle_height']:.2f}")
# 计算株高并保留两位小数
zhugao = round((result['average_person_height'] / result['average_bicycle_height']) * 370, 2)
print(f"株高: {zhugao}")
else:
print(f"Error: {response.json()['error']}")