|
import os |
|
import sys |
|
import time |
|
import cv2 |
|
import numpy as np |
|
import pandas as pd |
|
from rknnlite.api import RKNNLite |
|
|
|
pd.set_option("display.max_rows", 1000) |
|
|
|
dim = 448 |
|
thresh = 0.5 |
|
|
|
|
|
rknn_lite = RKNNLite(verbose=False) |
|
|
|
|
|
ret = rknn_lite.load_rknn("model.rknn") |
|
if ret != 0: |
|
print('加载RKNN模型失败') |
|
exit(ret) |
|
|
|
|
|
ret = rknn_lite.init_runtime() |
|
if ret != 0: |
|
print('初始化运行时环境失败') |
|
exit(ret) |
|
|
|
label_names = pd.read_csv("selected_tags.csv") |
|
|
|
target_img = "input.jpg" if len(sys.argv) < 2 else sys.argv[1] |
|
|
|
try: |
|
|
|
|
|
img = cv2.imread(target_img) |
|
if img is None: |
|
print(f"无法读取图像: {target_img}") |
|
exit(1) |
|
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
|
|
|
|
|
if img.shape[2] == 4: |
|
img = img[:, :, :3] |
|
elif len(img.shape) == 2: |
|
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) |
|
|
|
|
|
h, w = img.shape[:2] |
|
if h > w: |
|
diff = h - w |
|
pad_left = diff // 2 |
|
pad_right = diff - pad_left |
|
img = cv2.copyMakeBorder(img, 0, 0, pad_left, pad_right, |
|
cv2.BORDER_CONSTANT, value=(255, 255, 255)) |
|
elif w > h: |
|
diff = w - h |
|
pad_top = diff // 2 |
|
pad_bottom = diff - pad_top |
|
img = cv2.copyMakeBorder(img, pad_top, pad_bottom, 0, 0, |
|
cv2.BORDER_CONSTANT, value=(255, 255, 255)) |
|
|
|
|
|
img = cv2.resize(img, (dim, dim), interpolation=cv2.INTER_AREA) |
|
|
|
|
|
img = img.astype(np.float32) |
|
img = np.expand_dims(img, 0) |
|
print(img.shape) |
|
|
|
|
|
|
|
|
|
start = time.time() |
|
outputs = rknn_lite.inference(inputs=[img], data_format="nhwc") |
|
end = time.time() |
|
print(f"Inference time: {end - start} seconds") |
|
probs = outputs[0] |
|
print(probs.shape) |
|
|
|
|
|
label_names["probs"] = probs[0] |
|
found_tags = label_names[label_names["probs"] > thresh][["tag_id", "name", "probs"]] |
|
print(found_tags) |
|
|
|
finally: |
|
|
|
rknn_lite.release() |