使用step方法检索图像的bgr值的代码有什么问题

What is wrong with this code to retrieve bgr values of an image using the step method

本文关键字:代码 什么 问题 bgr 方法 检索 图像 使用 step      更新时间:2023-10-16

这是我从信誉良好的来源获得的代码,但它不起作用:

    Mat img = imread("/home/w/d1",CV_LOAD_IMAGE_COLOR);
        unsigned char *input = (unsigned char*)(img.data);
       int i,j,r,g,b;
        for(int i = 0;i < img.rows ;i++){
                for(int j = 0;j < img.cols ;j++){
                    b = input[img.step * j + i ] ;
                    g = input[img.step * j + i + 1];
                    r = input[img.step * j + i + 2];
            cout << b << g <<r;
                }
            }

当我运行它时,输出与我做 cout <<img 时不同;我认为这可能与新的C++界面有关。如果是这样并且我应该使用 step1 方法,有人可以告诉我如何使用 step1 方法更新我的代码以访问 BGR 值。我找不到有关如何使用步骤1的在线文档。提前感谢任何帮助。

你的代码看起来基本上是正确的,但据我所知,你的排序是错误的。您必须访问

value = data[img.step*ROW + COL]但您切换了行和列。

编辑:此外,您需要将 COL 乘以通道数:

value = data[img.step*ROW + #channels*COL + currentChannel]

尝试:

Mat img = imread("/home/w/d1",CV_LOAD_IMAGE_COLOR);
    unsigned char *input = (unsigned char*)(img.data);
   int i,j,r,g,b;
    for(int i = 0;i < img.rows ;i++){
            for(int j = 0;j < img.cols ;j++){
                b = input[img.step * i + 3*j ] ; // 3 == img.channels()
                g = input[img.step * i + 3*j + 1];
                r = input[img.step * i + 3*j + 2];
        cout << b << g <<r;
            }
        }

也许你想避免使用"原始数据"方法:

for(int i=0; i<img.rows; i++) {
    for(int j=0; j<img.cols; j++) {
        Vec3b pix = img.at<Vec3b>(i,j);
        cout << int(pix[0]) << int(pix[1]) << int(pix[2]) << endl;
    }
}