0

下面,我有一个使用 CImg 库 (http://cimg.sourceforge.net/) 的简单程序,它遍历图像的像素并根据其灰度值(光或黑暗的)。非常奇怪的是,每次运行程序(使用相同的输入)时,我都会得到不同的结果。

如果我做

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;
}

我已经阅读了一段时间,但我刚刚注册,所以我无法发布我正在使用的示例图像。我将只描述它们 - 它们是 10 像素 x 10 像素的 png 图像,包含黑白图案,使用 Photoshop CS5 创作。

4

1 回答 1

2

如果您的输入 .png 文件是灰度文件(仅一个通道,因为 .png 格式允许),那么您的 Gval 和 Bval 可能被分配了从无效内存访问中获取的随机值。因此,您的 AvgVal 可能是错误的,并且每次运行程序时生成的图像都可能不同。

于 2012-04-02T08:05:29.553 回答