Below, I have a simple program which uses the CImg library (http://cimg.sourceforge.net/) which iterates through the pixels of an image and outputs either a 0 or 1 for each pixel based on its grayscale value (light or dark). What’s quite strange is that I’m getting different results every time I run the program (with the same input).
If I do
image.display()
it works as expected, so it seems CImg is reading the image properly. However, if I attempt to print AvgVal in the inner for loop, I get different values every time. I’m using OSX 10.7.3 and gcc 4.2.1, if that makes any difference.
#include <iostream>
#include <fstream>
#include <stdexcept>
#include "CImg-1.4.9/CImg.h"
using namespace cimg_library;
int main(int argc, char *argv[]) {
if (argc != 3) {
std::cout << "Usage: acepp inputfile outputfile" << std::endl;
}
else {
std::ofstream outputFile(argv[2]);
if (!outputFile.is_open()) throw std::runtime_error("error: cannot open file for writing");
CImg<unsigned char> image(argv[1]);
int RVal, GVal, BVal, AvgVal, outBit;
for (int iHeight = 0; iHeight < image.height(); iHeight++) {
for (int iWidth = 0; iWidth < image.width(); iWidth++) {
RVal = image(iWidth,iHeight,0,0);
GVal = image(iWidth,iHeight,0,1);
BVal = image(iWidth,iHeight,0,2);
AvgVal = (RVal + GVal + BVal) / 3;
outBit = 1;
if (AvgVal > 127) outBit = 0; // low is dark, high is light
outputFile << outBit;
}
outputFile << std::endl;
}
outputFile.close();
std::cout << "Done writing to: " << argv[2] << std::endl;
}
return 0;
}
I’ve been reading SO for a while, but I just registered, so I can’t post the example images I’m using. I’ll just describe them – they were 10px x 10px png images containing black and white patterns, authored using Photoshop CS5.
If your input .png file is a grayscale one (one channel only, as it is permitted by the .png format), then probably, your Gval and Bval are assigned with random values taken from invalid memory access. As a consequence, your AvgVal may be wrong, and resulting image may be different each time you run the program.