- 本文承接https://blog.csdn.net/yohnyang/article/details/130367802
- 总结一下在使用Opencv中图像矩阵Mat数据赋值时的内存拷贝字节
测试代码C++
#include<iostream>
#include<opencv2/opencv.hpp>void main()
{//cv::Mat A = (cv::Mat_<float>(3, 3) << 1, 0, 0, 0, 1, 1, 0, 0, 1);int wh = 1200;cv::Mat A = cv::Mat(wh, wh, CV_8UC1, cv::Scalar::all(128));cv::Mat B, C;#if 1auto t0 = cv::getTickCount();B = A;B.at<float>(1, 1) = 8;auto t1 = cv::getTickCount();auto t01 = float(t1 - t0) / cv::getTickFrequency() * 1000;std::cout << cv::format("直接赋值耗时:%.2f ms\n", t01);#endift0 = cv::getTickCount();C = A.clone();C.at<float>(1, 1) = 8;t1 = cv::getTickCount();t01 = float(t1 - t0) / cv::getTickFrequency() * 1000;std::cout << cv::format("图像clone耗时:%.2f ms\n", t01);t0 = cv::getTickCount();//unsigned char* buffer = new unsigned char[A.rows * A.cols * A.channels()];//针对8通道可以,float或者double另行讨论cv::Mat D = cv::Mat(A.size(), A.type());memcpy(D.data, A.data, A.rows * A.cols * A.channels());t1 = cv::getTickCount();t01 = float(t1 - t0) / cv::getTickFrequency() * 1000;std::cout << cv::format("memcpy耗时:%.2f ms\n", t01);std::cout << "go!\n";}
- 输出:
直接赋值耗时:0.00 ms
图像clone耗时:0.76 ms
memcpy耗时:0.51 ms
- 若把图像大小设为3000,则 差距就很明显了
int wh = 3000;
cv::Mat A = cv::Mat(wh, wh, CV_8UC1, cv::Scalar::all(128));
- 结果如下:
直接赋值耗时:0.00 ms
图像clone耗时:4.84 ms
memcpy耗时:2.53 ms