OpenCV CopyTo 用法

/** @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.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值