• 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

  • 相关阅读:
    ThinkPHP讲解(一)框架基础
    smarty简单介绍
    留言板
    文件系统处理
    文件上传(带有预览模式)
    文件上传(无预览模式版)
    注册、登陆、审核练习
    session讲解(二)——商城购物车练习
    session讲解(一)——登录网页练习
    P6216 回文匹配
  • 原文地址:https://www.cnblogs.com/ronaldHU/p/15724771.html
Copyright © 2020-2023  润新知