使用Magick ++获取像素颜色?

时间:2011-10-06 18:00:55

标签: c++ imagemagick magick++

我已经问过这个问题,但那是FreeImage。现在我正在尝试使用ImageMagick执行相同的操作(更正确,使用Magick++)。

我所需要的只是获取图像中像素的RGB值,并能够将其打印到屏幕上。我在ImageMagick论坛上问了这个问题,但似乎没有人在那里。 :-(任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:12)

版本6 API

鉴于“图片”对象,您必须请求“像素缓存”,然后使用它。文档为herehere

// load an image
Magick::Image image("test.jpg");
int w = image.columns();
int h = image.rows();

// get a "pixel cache" for the entire image
Magick::PixelPacket *pixels = image.getPixels(0, 0, w, h);

// now you can access single pixels like a vector
int row = 0;
int column = 0;
Magick::Color color = pixels[w * row + column];

// if you make changes, don't forget to save them to the underlying image
pixels[0] = Magick::Color(255, 0, 0);
image.syncPixels();

// ...and maybe write the image to file.
image.write("test_modified.jpg");

版本7 API

版本7中对像素的访问权限发生了变化(请参阅:porting),但仍然存在低级别访问权限:

MagickCore::Quantum *pixels = image.getPixels(0, 0, w, h);

int row = 0;
int column = 0;
unsigned offset = image.channels() * (w * row + column);
pixels[offset + 0] = 255; // red
pixels[offset + 1] = 0;   // green
pixels[offset + 2] = 0;   // blue

答案 1 :(得分:2)

@ Sga的答案对我不起作用,我使用ImageMagick-7.0.7-Q8(8位深度)库。

以下是我的工作方式,逐像素扫描图像并输出每个RGB值:

// "InitializeMagick" called beforehand!
void processImage()
{
    std::ifstream fin;

    std::stringstream fs;
    fs << "/img.png";
    std::cout << "Opening image \"" << fs.str() << "\".." << std::endl;

    try
    {
        Image img;
        img.read( fs.str() );
        int imgWidth = img.columns();
        int imgHeight = img.rows();

        std::cout << "Image width: " << imgWidth << std::endl;
        std::cout << "Image height: " << imgHeight << std::endl;
        std::cout << "Image channels: " << img.channels() << std::endl;

        img.modifyImage();

        for ( int row = 0; row <= imgHeight; row++ )
        {
            for ( int column = 0; column <= imgWidth; column++ )
            {
                ColorRGB px = img.pixelColor( column, row );
                std::cout << "Pixel " << column << "," << row << " R: " << px.red() << " G: " << px.green() <<
                            " B: " << px.blue() << std::endl;
            }
        }

    }
    catch ( Magick::Exception & error )
    {
        std::cerr << "Caught Magick++ exception: " << error.what() << std::endl;
    }

    fin.close(); // Close the file
}