algN/test/cuda/test.py

89 lines
2.9 KiB
Python
Raw Normal View History

2025-08-23 10:12:26 +08:00
import time
from pathlib import Path
import GPUtil
import cv2
import numpy as np
import torch
from PIL import ImageFont, Image, ImageDraw
# print(Path(__file__)) # 表示当前脚本文件的路径
# print(Path(__file__).parent) # 表示当前路径的父级目录
# import time
# from contextlib import contextmanager
#
# @contextmanager
# def timer():
# start_time = time.time()
# yield
# end_time = time.time()
# print('Time elapsed:', end_time - start_time)
# # 使用上下文管理器
# with timer():
# time.sleep(1)
# print(torch.cuda.is_available())
# print(GPUtil.getGPUs()[0].name)
# def get_first_gpu_name():
# gps = GPUtil.getGPUs()
# if gps is None or len(gps) == 0:
# raise Exception("未获取到gpu资源, 先检测服务器是否已经配置GPU资源")
# return gps[0].name
# gpu_name = get_first_gpu_name()
# aa = [g for g in ['3090', '2080', '4090', 'A10'] if g in gpu_name]
# print(aa)
#
# import tensorrt as trt
# # 定义反序列化引擎文件的函数
# def deserialize_engine_from_file(engine_file_path):
# runtime = trt.Runtime(trt.Logger())
# engine = None
# with open(engine_file_path, "rb") as f:
# while True:
# data = f.read(1024 * 1024)
# if not data:
# break
# tmp_engine = runtime.deserialize_cuda_engine(data)
# if engine is None:
# engine = tmp_engine
# else:
# for i in range(tmp_engine.num_bindings):
# engine.set_binding_shape(i, tmp_engine.get_binding_shape(i))
# return engine
# engine_file_path = "/path/to/engine_file.engine"
# s = time.time()
# engine = deserialize_engine_from_file(engine_file_path)
# print("1 加载trt文件时间", time.time() - s)
# s1 = time.time()
# with open(engine_file_path, "rb") as f1, trt.Runtime(trt.Logger(trt.Logger.ERROR)) as runtime:
# model = runtime.deserialize_cuda_engine(f1.read())
# print("2 加载trt文件时间", time.time() - s1)
def get_label_array(color=None, label=None, outfontsize=None, fontpath="conf/platech.ttf"):
# Plots one bounding box on image 'im' using PIL
fontsize = outfontsize
font = ImageFont.truetype(fontpath, fontsize, encoding='utf-8')
x,y,txt_width, txt_height = font.getbbox(label)
print(x,y,txt_width, txt_height)
im = np.zeros((txt_height, txt_width, 3), dtype=np.uint8)
im = Image.fromarray(im)
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, txt_width, txt_height], fill=tuple(color))
draw.text((0, -3), label, fill=(255, 255, 255), font=font)
im_array = np.asarray(im)
# if outfontsize:
# scaley = outfontsize / txt_height
# im_array = cv2.resize(im_array, (0, 0), fx=scaley, fy=scaley)
return im_array
aaa = time.time()
im_array = get_label_array(color=(0, 255, 0), label="排口", outfontsize=40, fontpath="platech.ttf")
print(time.time() - aaa)
cv2.imshow("frame", im_array)
cv2.waitKey(0)