c++imagemagickmagick++

Getting pixel color with Magick++?


I've already asked this question, but that was about FreeImage. Now I'm trying to do the same thing with ImageMagick (to be more correct, with Magick++).

All I need is to get the RGB value of pixels in an image with the ability to print it out onto the screen. I asked this in the ImageMagick forum, but it seems there is nobody there. :-( Can anybody help, please?


Solution

  • 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