操作 cv::MAT 的像素只是不生效

Manipulating pixels of a cv::MAT just doesn't take effect

下面的代码只是用来加载一个图像,用一个常量值填充它并再次保存它。 当然,这还没有目的,但它仍然行不通。 我可以在循环中读取像素值,但所有更改均无效,并在加载文件时保存文件。 想我在这里准确地遵循了 "efficient way":http://docs.opencv.org/2.4/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html

int main()
{
    Mat im = imread("C:\folder\input.jpg");

    int channels = im.channels();
    int pixels = im.cols * channels;

    if (!im.isContinuous())
    { return 0; } // Just to show that I've thought of that. It never exits here.


    uchar* f = im.ptr<uchar>(0);

    for (int i = 0; i < pixels; i++)
    {
        f[i] = (uchar)100;
    }

    imwrite("C:\folder\output.jpg", im);

    return 0;
}

cvtColor() 等普通 cv 函数正在按预期生效。 通过数组的更改是否以某种方式发生在缓冲区上?

非常感谢!

问题是您没有查看图像中的所有像素。您的代码只查看 im.cols*im.channels(),与图像大小 (im.cols*im.rows*im.channels()) 相比,这是一个相对较小的数字。当使用指针在 for 循环中使用时,它只会为图像中的几行设置一个值(如果仔细观察,您会发现保存的图像将设置这些值)。

下面是更正后的代码:

int main()
{
    Mat im = imread("C:\folder\input.jpg");

    int channels = im.channels();
    int pixels = im.cols * im.rows * channels;

    if (!im.isContinuous())
    { return 0; } // Just to show that I've thought of that. It never exits here.


    uchar* f = im.ptr<uchar>(0);

    for (int i = 0; i < pixels; i++)
    {
        f[i] = (uchar)100;
    }

    imwrite("C:\folder\output.jpg", im);

    return 0;
}