Page 1 of 1
Get color of pixel with Magick++
Posted: 2011-10-04T10:06:35-07:00
by ghostmansd
Hello to all forum users! I need your help. I'm writing a small application, which needs a possibility to get color of any pixel in image. How can I get it with Magic++?
Thank you very much for your answer!
Re: Get color of pixel with Magick++
Posted: 2012-02-15T08:21:42-07:00
by dc87
Yes, refer to the Magick++ documentation on,
http://www.imagemagick.org/Magick++/Documentation.html
and for pixels in particular,
http://www.imagemagick.org/Magick++/Image.html#columns
Look at bottom section, 'Low-level image pixel access'
The Pixels Class also provides pixel access, look at
http://www.imagemagick.org/Magick++/Pixels.html
Here some sample code, that converts all black pixels to blue and all others to yellow. Read from input.tif and Write to output.tif
Code: Select all
#include <Magick++.h>
#include <iostream>
using namespace std;
using namespace Magick;
int main(void) {
Color black("black");
Color blue("blue");
Color yellow("yellow");
Image tifImage("input.tif");
size_t rows=1586, columns=1256;
tifImage.modifyImage();
tifImage.classType( DirectClass );
PixelPacket *tifPixels = tifImage.getPixels(0,0,columns,rows);
for(ssize_t i=0; i<columns*rows; i++){
if ( *(tifPixels+i) == black ){
*(tifPixels+i) = blue;
} else {
*(tifPixels+i) = yellow;
}
}
tifImage.syncPixels();
tifImage.write("output.tif");
return 0;
}
You can also get access to individual channels (RGBA) via other methods/attributes.
Code: Select all
Quantum red, green, blue;
red = tifPixels[i].red; // or tifPixels[i].redQuantum
green = tifPixels[i].green; // or tifPixels[i].greenQuantum
blue = tifPixels[i].blue; // or tifPixels[i].blueQuantum
Re: Get color of pixel with Magick++
Posted: 2014-02-12T14:13:36-07:00
by Davide
Resuming this old but pertinent thread, I found myself in trouble when trying to extract the integer value of channel's pixels.
Here's my code.
Cout always prints 65535, whatever image file is processed, whatever coordinates the pixel is picked from. Since the image is grayscale, I'd expect I should only need to extract color values from one channel.
Code: Select all
int main(int argc, char *argv[]) {
InitializeMagick(NULL);
Image img;
ColorGray val;
img.read(argv[1]);
int w = img.columns();
int h = img.rows();
img.type(GrayscaleType);
PixelPacket *pixels = img.getPixels(0, 0, w, h);
val = pixels[w * 135 + 234];
cout << "val: " << val.redQuantum() << endl;
}
Edit: "Solved". I happened to have a full set of completely white images over my text-only SSH.