import time
from ctypes import *
import cv2
import numpy as np
import numpy.ctypeslib as npct
import os
class Detector():
def __init__(self, par,bin, dll_path):
self.ncnn = CDLL(dll_path)
self.ncnn.Detect.argtypes = [POINTER(c_ubyte), c_int, c_int, c_int,c_int,
npct.ndpointer(dtype=np.float32, ndim=2, shape=(50, 6), flags="C_CONTIGUOUS")]
self.ncnn.Init.argtypes = [c_void_p,c_void_p]
self.ncnn.Init(par,bin)
def predict(self, img):
rows, cols = img.shape[0], img.shape[1]
res_arr = np.zeros((50, 6), dtype=np.float32)
self.ncnn.Detect(img.ctypes.data_as(POINTER(c_ubyte)), c_int(rows), c_int(cols), 352, 4, res_arr)
self.bbox_array = res_arr[~(res_arr == 0).all(1)]
return self.bbox_array
def free(self):
self.ncnn.ncnn_clear()
def visualize(img, bbox_array):
for temp in bbox_array:
bbox = [temp[0], temp[1], temp[2], temp[3]] # xywh
clas = int(temp[4])
score = temp[5]
cv2.rectangle(img, (int(temp[0]), int(temp[1])), (int(temp[2]), int(temp[3])),
(105, 237, 249), 2)
img = cv2.putText(img, "class:" + str(clas) + " " + str(round(score, 2)), (int(temp[0]), int(temp[1]) - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (105, 237, 249), 1)
return img
p = os.getcwd()
det = Detector(par=str.encode(p) + b"\\FastestDet.param",bin=str.encode(p) + b"\\FastestDet.bin", dll_path=p + "\\fastDet.dll") # b'' is needed
while True:
img = cv2.imread("2.jpg")
t1 = time.time()
result = det.predict(img)
img = visualize(img, result)
print(time.time() - t1)
cv2.imshow("img", img)
cv2.waitKey(1)
# det.free()
文件项目 会传资源下载 请自己查找