/** @brief Copies the matrix to another one.
The method copies the matrix data to another matrix. Before copying the data, the method invokes :
@code
m.create(this->size(), this->type());
@endcode
so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the
function does not handle the case of a partial overlap between the source and the destination
matrices.
When the operation mask is specified, if the Mat::create call shown above reallocates the matrix,
the newly allocated matrix is initialized with all zeros before copying the data.
@param m Destination matrix. If it does not have a proper size or type before the operation, it is
reallocated.
*/
void copyTo( OutputArray m ) const;
/** @overload
@param m Destination matrix. If it does not have a proper size or type before the operation, it is
reallocated.
@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
*/
void copyTo( OutputArray m, InputArray mask ) const;
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat srcImage = imread("D:/self_study/exampleForOpenCV/pictureSource/Architecture.jpg");
if (!srcImage.data) return -1;
Mat grayImage;
imshow("srcImage", srcImage);
cvtColor(srcImage, grayImage, CV_BGR2GRAY);
Mat blurMat;
blur(grayImage, blurMat, Size(3, 3)); //均值滤波
Mat edgeImage;
Canny(blurMat, edgeImage, 50, 150, 3);
imshow("cannyImage", edgeImage);
Mat dstOne, dstTwo;
srcImage.copyTo(dstOne); // 在执行copy之前,会自动分配dstOne的大学和type. 接着会把srcImage 的内容copy到dstOne.
srcImage.copyTo(dstTwo, edgeImage); // 同上,edgeImage的大小是和srcImage一致的,copy的时候只复制 edgeImage 矩阵中非零值处的所对应的srcImage矩阵中相同位置处的值到dstTwo, 即复制的值是srcImage中的,但复制哪个位置,是由edgeImage决定的,如edgeImage.at<uchar>(10, 20) = 255, 在这个位置处的值非零,那复制 srcImage.at<uchar>(10, 20) 处值到dstTwo.
imshow("dstOne", dstOne);
imshow("dstTwo", dstTwo);
waitKey(0);
return 0;
}
效果图如下所示:
如下是srcImage:
如下是Canny边缘检测图
如下是dstOne,其效果与srcImage一样:
如下是dstTwo图,图中有彩色,是因为保留的src中的三通道值,即dstTwo的channel是3.