Cycle through pixels with opencv

后端 未结 7 2198
情深已故
情深已故 2020-12-07 17:46

How would I be able to cycle through an image using opencv as if it were a 2d array to get the rgb values of each pixel? Also, would a mat be preferable over an iplimage for

7条回答
  •  攒了一身酷
    2020-12-07 18:26

    If you want to modify RGB pixels one by one, the example below will help!

    void LoopPixels(cv::Mat &img) {
        // Accept only char type matrices
        CV_Assert(img.depth() == CV_8U);
    
        // Get the channel count (3 = rgb, 4 = rgba, etc.)
        const int channels = img.channels();
        switch (channels) {
        case 1:
        {
            // Single colour
            cv::MatIterator_ it, end;
            for (it = img.begin(), end = img.end(); it != end; ++it)
                *it = 255;
            break;
        }
        case 3:
        {
            // RGB Color
            cv::MatIterator_ it, end;
            for (it = img.begin(), end = img.end(); it != end; ++it) {
                uchar &r = (*it)[2];
                uchar &g = (*it)[1];
                uchar &b = (*it)[0];
                // Modify r, g, b values
                // E.g. r = 255; g = 0; b = 0;
            }
            break;
        }
        }
    }
    

提交回复
热议问题