How to open and read the pixels of an image in c++? Read them in the form of X, Y and to know the color.
Reading the color of a pixel from an image file using the Magick++ library
#include <Magick++.h>
#include <iostream>
using namespace Magick;
using namespace std;
int main(int argc, char **argv) {
try {
InitializeMagick(*argv);
Image img("C:/test.bmp");
ColorRGB rgb(img.pixelColor(0, 0)); // ie. pixel at pos x=0, y=0
cout << "red: " << rgb.red();
cout << ", green: " << rgb.green();
cout << ", blue: " << rgb.blue() << endl;
}
catch ( Magick::Exception & error) {
cerr << "Caught Magick++ exception: " << error.what() << endl;
}
return 0;
}
Either you use an existing library or you write your own code. Generally the first approach is better since an image file format is often more complex than it seems on the surface and you may end up with upside down images or incorrect color component order if you are not careful.
Depending on your requirements you may also need to take capabilities of the format in consideration. If support for high dynamic range is interesting, OpenEXR is a great choice, if it's not it's probably just inconvenient since it does not have as big support among other programs as for example PNG.
Here are two libraries I often turn to when needing to read and write images: libpng, OpenExr
If you are going to be working with images you should look into the OpenCV library, it has pretty much everything you need to work with images.
OpenCV 2.0 came out a couple of months ago and its very friendly with C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With