1. 纯python部署(onnx模型)
import os
import time
import numpy as np
import onnxruntime
import json
import cv2
def imnormalize(img, mean, std, to_rgb=True):
"""Normalize an image with mean and std.
Args:
img (ndarray): Image to be normalized.
mean (ndarray): The mean to be used for normalize.
std (ndarray): The std to be used for normalize.
to_rgb (bool): Whether to convert to rgb.
Returns:
ndarray: The normalized image.
"""
img = img.copy().astype(np.float32)
# cv2 inplace normalization does not accept uint8
mean = np.float64(mean.reshape(1, -1))
stdinv = 1 / np.float64(std.reshape(1, -1))
if to_rgb:
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) # inplace
cv2.subtract(img, mean, img) # inplace
cv2.multiply(img, stdinv, img) # inplace
return img
def letterbox_image(img, input_dim, fill_value):
"""
resize image with unchanged aspect ratio using padding
让原图的高宽乘以同一个数,这样就不会改变比例,而这个数就是min( 高缩放的比例,宽缩放的比例),然后padding周围区域使得缩放到指定大小。
缩小: (2000, 4000) -> (200,200), min(200/4000, 200/2000) = 1/20, 2000 * 1/20 = 100, 4000 * 1/20 = 200
新的尺度(100, 200),再padding
放大: (50, 100) -> (200, 200), min(4, 2) = 2, 50 * 2 = 100, 100 * 2 = 200
新的尺度(100, 200),再padding
:param fill_value: int. Padding value
:param img: original image.
:param input_dim: (w, h). 缩放后的尺度
:return:
"""
orig_w, orig_h = img.shape[1], img.shape[0]
input_w, input_h = input_dim # 缩放(orig_w, orig_h) -> (input_w, input_h)
# 1,根据缩放前后的尺度,获取有效的新的尺度(new_w, new_h)
min_ratio = min(input_w / orig_w, input_h / orig_h)
new_w = int(orig_w * min_ratio) # (new_w, new_h)是高宽比不变的新的尺度
new_h = int(orig_h * min_ratio)
resized_image = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_CUBIC)