c++ 中的直方图代码显示了一些疯狂的意外数字
histogram code in c++ shows some crazy unexpected numbers
我写了一个小程序来确定图片的直方图作为我任务的一部分:
void histogram(const SimpleGrayImage &img, long (&tab)[256]) { //SimpleGrayImage is a given class from our prof
int val = 0;
int count = 1;
while (val < 256) {
for (int i = 0; i < img.height(); i++) {
for (int j = 0; j < img.width(); j++) {
if (val == img[i][j]) { //with img[][] you can get the integer value (between 0<256)
tab[val] = count;
count++;
}
}
}
count = 0;
val++;
}
}
下一步我将打印数组:
int main(){
SimpleGrayImage img(RESOURCES_PATH "/black.pgm"); //loads a black image with the resolution of 512x512
long arr[256];
histogram(img, arr);
for(int j=0;j<256;j++){
cout<<"grey tone: "<<j<<" count: "<<arr[j]<<"\n"<<endl;
}
}
当我运行这个程序时,控制台给出正确的信息:
grey tone: 0 count: 262144
。
.
.
其他灰色调(从 1-235)也提供了正确的信息 (0),但随后控制台显示了一些疯狂的数字,我无法解释为什么会这样:
grey tone: 236 count: 288392707021528753
grey tone: 237 count: 140734701956328
grey tone: 238 count: 21
grey tone: 239 count: 1
grey tone: 240 count: 4392816744
grey tone: 241 count: 140734851732223
grey tone: 242 count: 140734701956144
grey tone: 243 count: 140734851576438
grey tone: 244 count: 140734701956176
。
.
.
所以你们能给我一个解决我的问题的方法吗?
谢谢:)
如果某些值根本不存在,那么您没有将数组初始化为零这一事实打击了您。
试试这样的东西:
long arr[256];
for (int i = 0; i < 256; i++) {
arr[i] = 0;
}
histogram(img, arr);
或者,在您的 histogram
函数中处理初始化。
您忘记初始化数组。所以你正在打印一些你不知道是否有值的内存块。
运行 此代码在调用 histogram
之前初始化 arr
。
for (int i = 0; i < 256; i++)
arr[i] = 0;
我写了一个小程序来确定图片的直方图作为我任务的一部分:
void histogram(const SimpleGrayImage &img, long (&tab)[256]) { //SimpleGrayImage is a given class from our prof
int val = 0;
int count = 1;
while (val < 256) {
for (int i = 0; i < img.height(); i++) {
for (int j = 0; j < img.width(); j++) {
if (val == img[i][j]) { //with img[][] you can get the integer value (between 0<256)
tab[val] = count;
count++;
}
}
}
count = 0;
val++;
}
}
下一步我将打印数组:
int main(){
SimpleGrayImage img(RESOURCES_PATH "/black.pgm"); //loads a black image with the resolution of 512x512
long arr[256];
histogram(img, arr);
for(int j=0;j<256;j++){
cout<<"grey tone: "<<j<<" count: "<<arr[j]<<"\n"<<endl;
}
}
当我运行这个程序时,控制台给出正确的信息:
grey tone: 0 count: 262144
。 . .
其他灰色调(从 1-235)也提供了正确的信息 (0),但随后控制台显示了一些疯狂的数字,我无法解释为什么会这样:
grey tone: 236 count: 288392707021528753
grey tone: 237 count: 140734701956328
grey tone: 238 count: 21
grey tone: 239 count: 1
grey tone: 240 count: 4392816744
grey tone: 241 count: 140734851732223
grey tone: 242 count: 140734701956144
grey tone: 243 count: 140734851576438
grey tone: 244 count: 140734701956176
。 . .
所以你们能给我一个解决我的问题的方法吗? 谢谢:)
如果某些值根本不存在,那么您没有将数组初始化为零这一事实打击了您。
试试这样的东西:
long arr[256];
for (int i = 0; i < 256; i++) {
arr[i] = 0;
}
histogram(img, arr);
或者,在您的 histogram
函数中处理初始化。
您忘记初始化数组。所以你正在打印一些你不知道是否有值的内存块。
运行 此代码在调用 histogram
之前初始化 arr
。
for (int i = 0; i < 256; i++)
arr[i] = 0;