copy one channel of an image into another mat in opencv c++

To copy one channel of an image into another Mat in OpenCV using C++, you can use the split function to separate the channels of the source image, and then assign the desired channel to the corresponding channels of the destination Mat. Here's an example:

cv::Mat src = imread("source.png", cv::IMREAD_COLOR); // load source image
cv::Mat dst(src.rows, src.cols, src.type()); // create destination image with the same size and type as the source

std::vector<cv::Mat> channels;
cv::Mat blue, green, red;

// split the channels of the source image
cv::split(src, channels);

// assign the blue channel to the destination image
blue = channels[0];
dst = cv::Mat::zeros(src.rows, src.cols, CV_8UC1); // create a single-channel destination image
blue.copyTo(dst);

// assign the green channel to the blue and green channels of the destination image
green = channels[1];
for (int i = 0; i < dst.rows; i++) {
    for (int j = 0; j < dst.cols; j++) {
        dst.at<cv::Vec3b>(i, j)[0] = green.at<uchar>(i, j); // blue channel
        dst.at<cv::Vec3b>(i, j)[1] = green.at<uchar>(i, j); // green channel
    }
}

// assign the red channel to the red channel of the destination image
red = channels[2];
for (int i = 0; i < dst.rows; i++) {
    for (int j = 0; j < dst.cols; j++) {
        dst.at<cv::Vec3b>(i, j)[2] = red.at<uchar>(i, j); // red channel
    }
}

In this example, we load a source image with three channels (red, green, and blue) using the imread function. We then create a destination image with the same size and type as the source using the Mat constructor.

Next, we split the channels of the source image using the split function, and assign the desired channel to the corresponding channels of the destination Mat. For example, to copy the green channel to the blue and green channels of the destination image, we use a nested loop to iterate over each pixel of the destination image and assign the green channel value to the blue and green channels of the Vec3b vector.

Finally, we assign the red channel to the red channel of the destination image using a similar approach.

Note that the Mat::zeros function is used to create a single-channel destination image for the blue channel.

[1] [5]

References

Any other questions?