编写值时,数组索引似乎会滑动

时间:2014-11-23 19:08:03

标签: c++

我有一个Npp8u * image = new Npp8u[nWidth * nHeight];数组,用于存储灰度图像值。我将Npp8u定义为typedef unsigned char Npp8u;。当我尝试从任何像素中减去最低图像值时,会出现问题。

我使用此功能进行减法。

void SubtractValue(Npp8u * image, int width, int height, Npp8u value){
    int iValue = value;
    for (int i = 0; i < height; ++i){
        for (int j = 0; j < width; ++j){
            int indexVal = (image[i*width + j]);
            int newVal = indexVal - iValue;
            image[i*width + j] = (Npp8u) newVal;
        }
    }
}

这个功能的结果很奇怪。我使用Lena Image进行测试,这是原始图像。 enter image description here

如果值为85,我会得到以下图像 enter image description here

注意:原始图像是.pgm

阅读程序:

for (int i = 0; i < nHeight; ++i)
    for (int j = 0; j < nWidth; ++j)
        image[i*nWidth + j] = fgetc(fInput);

写作程序:

for (int i = 0; i < nHeight; ++i)
    for (int j = 0; j < nWidth; ++j)
        fputc(image[i*nWidth + j], fOutput);

更新:如果像素的值为10,即新换行符,则会出现问题。

1 个答案:

答案 0 :(得分:2)

由于您提到字符10导致问题,因此可能会怀疑您正在读取/写入的图像格式需要以“二进制”文件模式处理,因此ASCII 10不会被视为换行符。< / p>

因此,请确保以二进制模式打开文件(fopen使用"rb""wb"标志,具体取决于您是在阅读还是写作。