opencv学习日志4-深复制和浅复制

前言

这篇文章通过代码来讲述深复制和浅复制的区别

一、代码

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
int main()
{
	cv::Mat srcMat = imread("C://Users//john//Desktop//1.jpg");
	cv::Mat deepMat;
	cv::Mat shallowMat;
	shallowMat = srcMat;
	srcMat.copyTo(deepMat);
	int height = srcMat.rows;
	int width = srcMat.cols;
	for (int j = 0; j < height; j++)
	{
		for (int i = 0; i < width; i++)
		{
			uchar average = (srcMat.at<Vec3b>(j, i)[0] + srcMat.at<Vec3b>(j, i)[1] + srcMat.at<Vec3b>(j, i)[2]) / 3;
			if (average > 100)average = 255;
			if (average <= 100) average = 0;
			srcMat.at<Vec3b>(j, i)[0] = average;
			srcMat.at<Vec3b>(j, i)[1] = average;
			srcMat.at<Vec3b>(j, i)[2] = average;
		}
	}
	imshow("deep", deepMat);
	imshow("shallow", shallowMat);
	waitKey(0);

}

总结

因为深复制和浅复制的不同,浅复制指向的是同一片内存空间,所以会随着src改变而改变,深复制则不会改变

上一篇:Awesome-CV 解决中文显示


下一篇:OpenCV的读取与显示图像(c++)