【发布时间】:2012-04-01 23:54:43
【问题描述】:
下面,我有一个使用 CImg 库 (http://cimg.sourceforge.net/) 的简单程序,它遍历图像的像素并根据其灰度值为每个像素输出 0 或 1 (亮或暗)。非常奇怪的是,每次运行程序(使用相同的输入)时,我都会得到不同的结果。
如果我这样做
image.display()
它按预期工作,因此 CImg 似乎正在正确读取图像。但是,如果我尝试在内部 for 循环中打印 AvgVal,每次都会得到不同的值。我正在使用 OSX 10.7.3 和 gcc 4.2.1,如果这有什么不同的话。
#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;
}
我已经阅读 SO 有一段时间了,但我刚刚注册,所以我无法发布我正在使用的示例图片。我将只描述它们 - 它们是 10 像素 x 10 像素的 png 图像,包含黑白图案,使用 Photoshop CS5 创作。
【问题讨论】:
-
当您说“如果我尝试在内部 for 循环中打印 AvgVal”时,您如何打印 ArgVal。您从中获得的示例输出(包括预期输出)可以代替任何实际图像。