cv::Mat::copyTo() をお使いください。
cpp
1void cv::Mat::copyTo(OutputArray m, InputArray mask) const
- m: Destination matrix. If it does not have a proper size or type before the operation, it is reallocated.
- 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.
cpp
1#include <iostream>
2
3#include <opencv2/opencv.hpp>
4
5
6int main()
7{
8 // mat1[mat3 > 0] = mat2[mat3 > 0] と以下は同じ
9
10 cv::Mat mat1 = (cv::Mat_<float>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
11 std::cout << mat1 << std::endl;
12 // [1, 2, 3;
13 // 4, 5, 6;
14 // 7, 8, 9]
15
16 cv::Mat mat2 =
17 (cv::Mat_<float>(3, 3) << 11, 12, 13, 14, 15, 16, 17, 18, 19);
18 std::cout << mat2 << std::endl;
19 // [11, 12, 13;
20 // 14, 15, 16;
21 // 17, 18, 19]
22
23 cv::Mat mat3 = (cv::Mat_<float>(3, 3) << -1, -1, 1, -1, -1, -1, 1, -1, 1);
24 std::cout << mat3 << std::endl;
25 // [-1, -1, 1;
26 // -1, -1, -1;
27 // 1, -1, 1]
28
29 // mat3 > 0 の要素のみ mat2 の値を mat1 にコピーする。
30 mat2.copyTo(mat1, mat3 > 0);
31 std::cout << mat1 << std::endl;
32 // [1, 2, 13;
33 // 4, 5, 6;
34 // 17, 8, 19]
35}
36