如何使用1d数组更改2d数组中的值?

时间:2017-05-11 07:55:22

标签: c++

当其中一个数字等于num[]时,我想让a[][]的值替换所有k值。因此num的所有值都对应k处的每个位置。因此,例如当k达到20时,如果在2d数组中有20,我想用num[19]中的任何内容替换所有20,但每当我尝试它时,它们都会变成偏斜的数字而我找不到原因。我的for循环设置错误或者还有什么问题吗?

#include<iostream>

int main(){
//other code that uses a file to make 2d array
int width, height, maxval;
fin >> P2 >> width >> height >> maxval;
int **a = new int *[height];
for (int i = 0; i < height; i++)
    a[i] = new int[width];
for (int i = 0; i < height; i++)
{
    for (int j = 0; j < width; j++)
    {
        fin >> a[i][j];
    }
}

}


void eq(int **a, int h, int w) {

    int num[255];
double num1[255];
double prob[255], cumul[255]{ 0 };
double x, y, z=0;
for (int k = 1; k <= 255; k++)
{
    int temp = 0;
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {//counts the repeated pixel values 
            if (pix[i][j] == k)
            {
                temp += 1;
            }
        }
    }
    num1[k - 1] = temp;
}

for (int i = 0; i < 255; i++) {

    prob[i] = (num1[i] / (height*width));//show the decimal number of how many pixel values are in the image over the total
    cout << prob[i] << endl;
}

for (int i = 0; i < 255; i++) {
    y = prob[i];
    x = y + z;
    z = x;// adds all the probabilities to make the sum
    cumul[i] =x;    
    cout << cumul[i] << endl;
}

for (int i = 0; i < 255; i++) {

    num[i] =floor(cumul[i]*255);// converts the cumulative number to the new pixel value and sets it in a array

}

    for (int k = 1; k <= 255; k++) {//loop that is not coming out right
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {

                if (a[i][j] == k)
                {
                    a[i][j] =num[k-1];
                }
            }
        }
    }
}

基本上我正在制作一个处理直方图均衡的函数,以使pgm图像更清晰。在main函数中,我调用pgm文件并将所有像素值设置为2d数组。所以num[]是我创建新像素值的部分,但出于某种原因,每当我调用a[0][0]时,我应该得到的东西不是零或255,因为这两个值都意味着没有像素具有相应的强度,但每当我调用它时,我得到255或其他随机数。

1 个答案:

答案 0 :(得分:0)

如果我明白你想做什么,这一行:

a[i][j] =num[i];

应该是:

a[i][j] =num[k-1];

因为你想:

if( a[i][j] = k = 20){
  a[i][j] = num[k-1 = 19] 
 }