【问题标题】:C++/CImg inconsistent resultsC++/CImg 不一致的结果
【发布时间】: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。您从中获得的示例输出(包括预期输出)可以代替任何实际图像。

标签: c++ cimg


【解决方案1】:

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

【讨论】:

  • 谢谢,这就是导致问题的原因。我使用的 png 是单通道图像。万一其他人遇到这个问题 - 很容易解决。我使用了成员函数spectrum(),它返回图像中的通道数。然后我遍历所有通道,将值添加到累加器,最后将累加器除以 image.spectrum()
猜你喜欢
  • 1970-01-01
  • 2013-04-30
  • 2014-09-21
  • 2021-03-27
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多