How to set given channel of a cv::Mat to a given value efficiently without changing other channels?

后端 未结 4 810
走了就别回头了
走了就别回头了 2020-12-11 01:12

How to set given channel of a cv::Mat to a given value efficiently without changing other channels? For example, I want to set its fourth channel (alpha channel

4条回答
  •  天命终不由人
    2020-12-11 01:58

    Mat img;
    [...]
    const int cols = img.cols;
    const int step = img.channels();
    const int rows = img.rows;
    for (int y = 0; y < rows; y++) {
        unsigned char* p_row = img.ptr(y) + SELECTED_CHANNEL_NUMBER; //gets pointer to the first byte to be changed in this row, SELECTED_CHANNEL_NUMBER is 3 for alpha
        for (int x = 0; x < cols; x++) {
             *p_row = value;
             p_row += step; //Goes to the next byte to be changed
        }
    }
    

    Note: This works both for continuous and uncontinuous matrices, according to the use of the term for opencv: http://docs.opencv.org/modules/core/doc/basic_structures.html#bool%20Mat::isContinuous%28%29%20const

提交回复
热议问题