| 46 | } |
| 47 | |
| 48 | bool yolo::YOLO::init(const std::vector<unsigned char>& trtFile) |
| 49 | { |
| 50 | if (trtFile.empty()) |
| 51 | { |
| 52 | return false; |
| 53 | } |
| 54 | std::unique_ptr<nvinfer1::IRuntime> runtime = |
| 55 | std::unique_ptr<nvinfer1::IRuntime>(nvinfer1::createInferRuntime(sample::gLogger.getTRTLogger())); |
| 56 | if (runtime == nullptr) |
| 57 | { |
| 58 | return false; |
| 59 | } |
| 60 | this->m_engine = std::unique_ptr<nvinfer1::ICudaEngine>(runtime->deserializeCudaEngine(trtFile.data(), trtFile.size())); |
| 61 | |
| 62 | if (this->m_engine == nullptr) |
| 63 | { |
| 64 | return false; |
| 65 | } |
| 66 | this->m_context = std::unique_ptr<nvinfer1::IExecutionContext>(this->m_engine->createExecutionContext()); |
| 67 | if (this->m_context == nullptr) |
| 68 | { |
| 69 | return false; |
| 70 | } |
| 71 | if (m_param.dynamic_batch) // for some models only support static mutil-batch. eg: yolox |
| 72 | { |
| 73 | this->m_context->setBindingDimensions(0, nvinfer1::Dims4(m_param.batch_size, 3, m_param.dst_h, m_param.dst_w)); |
| 74 | } |
| 75 | m_output_dims = this->m_context->getBindingDimensions(1); |
| 76 | m_total_objects = m_output_dims.d[1]; |
| 77 | assert(m_param.batch_size <= m_output_dims.d[0]); |
| 78 | m_output_area = 1; |
| 79 | for (int i = 1; i < m_output_dims.nbDims; i++) |
| 80 | { |
| 81 | if (m_output_dims.d[i] != 0) |
| 82 | { |
| 83 | m_output_area *= m_output_dims.d[i]; |
| 84 | } |
| 85 | } |
| 86 | CHECK(cudaMalloc(&m_output_src_device, m_param.batch_size * m_output_area * sizeof(float))); |
| 87 | float a = float(m_param.dst_h) / m_param.src_h; |
| 88 | float b = float(m_param.dst_w) / m_param.src_w; |
| 89 | float scale = a < b ? a : b; |
| 90 | cv::Mat src2dst = (cv::Mat_<float>(2, 3) << scale, 0.f, (-scale * m_param.src_w + m_param.dst_w + scale - 1) * 0.5, |
| 91 | 0.f, scale, (-scale * m_param.src_h + m_param.dst_h + scale - 1) * 0.5); |
| 92 | cv::Mat dst2src = cv::Mat::zeros(2, 3, CV_32FC1); |
| 93 | cv::invertAffineTransform(src2dst, dst2src); |
| 94 | m_dst2src.v0 = dst2src.ptr<float>(0)[0]; |
| 95 | m_dst2src.v1 = dst2src.ptr<float>(0)[1]; |
| 96 | m_dst2src.v2 = dst2src.ptr<float>(0)[2]; |
| 97 | m_dst2src.v3 = dst2src.ptr<float>(1)[0]; |
| 98 | m_dst2src.v4 = dst2src.ptr<float>(1)[1]; |
| 99 | m_dst2src.v5 = dst2src.ptr<float>(1)[2]; |
| 100 | return true; |
| 101 | } |
| 102 | |
| 103 | void yolo::YOLO::check() |
| 104 | { |