ncnn::Mat opencv::Mat 互转
nihui 写的:https://github.com/Tencent/ncnn/wiki/use-ncnn-with-opencv
1、cv::Mat转ncnn::Mat
cv::Mat bgr = cv::Mat(img_h,img_w,CV_8UC3); ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
2、ncnn::Mat 转 cv::Mat
ncnn::Mat in_pad; ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
(1)uchar
cv::Mat Mat1(in_pad.h, in_pad.w, CV_8UC3);
in_pad.to_pixels(Mat1.data, ncnn::Mat::PIXEL_BGR2RGB);
(2)float
const float norm_vals[3] = { 1 / 255.f, 1 / 255.f, 1 / 255.f };
const float mean_vals[3] = { 0.f, 0.f, 0.f };
in_pad.substract_mean_normalize(mean_vals, norm_vals);
cv::Mat Mat2(in_pad.h, in_pad.w, CV_32FC3); float *pMat2Data = Mat2.ptr<float>(0); for (int c = 0; c < 3; c++) { int idx = 0; for (int i = 0; i < in_pad.h; i++) { for (int j = 0; j < in_pad.w; j++) { float t = ((float*)in_pad.data)[j + i * in_pad.w + c * in_pad.h * in_pad.w]; *(pMat2Data+2-c+idx) = t; idx += 3; } } }
(3)float,新
cv::Mat Mat2(in.h, in.w, CV_32FC3); float *pMat2Data = Mat2.ptr<float>(0); float* inData = (float*)in.data; int gOffset = in.cstep; int rOffset = in.cstep *2; for (int i = 0; i < in.cstep; i++, pMat2Data+=3) { *(pMat2Data + 0) = inData[i]; *(pMat2Data + 1) = inData[gOffset + i]; *(pMat2Data + 2) = inData[rOffset + i]; }