opencv读取图像实现python ToTensor
2021/12/23 20:08:46
本文主要是介绍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
这篇关于opencv读取图像实现python ToTensor的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程