Getting pixel color with Magick++?

孤人 提交于 2019-11-30 13:34:04

Version 6 API

Given an "Image" object, you have to request a "pixel cache", then work with it. Documentation is here and here:

// 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");

Version 7 API

Access to pixels has changed in version 7 (see: porting), but low-level access is still present:

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

@Sga's answer didn't work for me, I'm using the ImageMagick-7.0.7-Q8 (8 bit depth) library.

Here's how I did it, to scan an image pixel by pixel and output each one's RGB value:

// "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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!