Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++/不一致结果_C++_Cimg - Fatal编程技术网

C++ C++/不一致结果

C++ C++/不一致结果,c++,cimg,C++,Cimg,下面,我有一个使用CImg库的简单程序(http://cimg.sourceforge.net/)它遍历图像的像素,并根据其灰度值(亮或暗)为每个像素输出0或1。非常奇怪的是,每次运行程序(使用相同的输入)时,我都会得到不同的结果 如果我这样做 image.display() 它的工作原理与预期一致,因此似乎CImg正在正确读取图像。但是,如果我尝试在内部for循环中打印AvgVal,每次都会得到不同的值。我正在使用OSX 10.7.3和gcc 4.2.1,如果这有什么区别的话 #includ

下面,我有一个使用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;
}
#包括
#包括
#包括
#包括“CImg-1.4.9/CImg.h”
使用名称空间cimg_库;
int main(int argc,char*argv[]){
如果(argc!=3){

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

当您说“如果我尝试在内部for循环中打印AvgVal”时,您如何打印ArgVal。您从中获得的示例输出(包括预期输出)将很好地替代任何实际图像。谢谢,这就是导致问题的原因。我使用的png是单通道图像。如果其他人有此问题,则很容易修复。我使用了成员函数spectrum()它返回图像中的通道数。然后我遍历所有通道,将值添加到累加器中,最后将累加器除以image.spectrum()