opencv读取图像实现python ToTensor

 

 

实现toTensor

 resize_img.convertTo(resize_img, CV_32F, 1.0 / 255);  //divided by 255
        resize_img -= 0.5f;  // mean
        resize_img /= 0.5f;   // std
        cv::Mat channels[3]; //借用来进行HWC->CHW
        cv::split(resize_img, channels);
        std::vector<float> inputTensorValues;
        for (int i = 0; i < resize_img.channels(); i++)  // BGR2RGB, HWC->CHW
        {
            std::vector<float> data = std::vector<float>(channels[2 - i].reshape(1, resize_img.cols * resize_img.rows));
            inputTensorValues.insert(inputTensorValues.end(), data.begin(), data.end());
        }


// inputTensorValues 可以作为输入数据送入onnxruntime

实现toTensor+normalize

 float mean[]={0.5f,0.5f,0.5f};
        float std_val[]={0.5f,0.5f,0.5f};
        resize_img.convertTo(resize_img, CV_32F, 1.0 / 255);  //divided by 255

        cv::Mat channels[3]; //借用来进行HWC->CHW
        cv::split(resize_img, channels);
        std::vector<float> inputTensorValues;
        for(int i=0; i< resize_img.channels(); i++)
        {
       channels[i] -= mean[i];  // mean
        channels[i] /= std_val[i];   // std
        }
        for (int i = 0; i < resize_img.channels(); i++)  // BGR2RGB, HWC->CHW
        {
            std::vector<float> data = std::vector<float>(channels[2 - i].reshape(1, resize_img.cols * resize_img.rows));
            inputTensorValues.insert(inputTensorValues.end(), data.begin(), data.end());
        }


// inputTensorValues 可以作为输入数据送入onnxruntime

  

 public float[] toTensor(Mat mat) {
       
        mat.convertTo(mat, CvType.CV_32F);
        ArrayList<Mat> dst = new ArrayList<>(3);
        Core.split(mat, dst);
        ArrayList<Float> arrayList = new ArrayList<>();
        for (int i = dst.size() - 1; i >= 0; i--) { # bgr --> rgb OpenCV默认读取的图像是BGR
            arrayList.addAll(Floats.asList(matToFloat(dst.get(i))));
        }

        Float t[] = new Float[arrayList.size()];
        arrayList.toArray(t);
        float[] data = new float[t.length];
        for (int i = 0; i < t.length; i++) {
            data[i] = t[i] / 255.0f;
        }
        return data;
    }

  

 https://www.cxyzjd.com/article/znsoft/117128781

上一篇:Pytorch入门上 —— Dataset、Tensorboard、Transforms、Dataloader


下一篇:css常用代码大全,html+css代码