gpt4 book ai didi

java - 查找并打印多维数组中值的平方的平均值

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:28 26 4
gpt4 key购买 nike

我一直在解决一个非常简单的问题,但由于某种原因我似乎无法解决这个问题,但我觉得我已经很接近了。我想要一些关于我的距离/距离以及我可以移动的方向的信息。

基本上,我将图像作为 pnm 文件接收,并将像素值接收到二维数组中。然后我必须取一个 4 像素的正方形,找到平均值,然后将其打印到一个新文件中,从而有效地缩小图像。
例如包含 4 个像素的正方形:

0 10

12 14
变成只有一个值:9

主要关注的是我计算平均值的循环。我增加 2 是因为我只想查看值的平方。我访问 4 个像素的索引并用它们初始化临时变量,然后找到写入输出文件的平均值。

不幸的是,我似乎没有得到平均值,并且打印的图像完全错误。任何帮助将不胜感激,谢谢!

主编辑。好吧,在大家给我的帮助下,我似乎已经解决了这个问题。问题不是由平均像素的计算引起的,而是由二维数组的初始化引起的。我在声明时混淆了两个宽度和高度像素值,因此我采用并使用了错误的像素进行计算。在最终版本中,代码在修复后可以很好地处理任何尺寸的图片。感谢大家的帮助,特别是@Geo 指出了问题!

记住:数组[行][列]。

最终代码。

        /**
* I take in the values from the pnm file and read in the file type, width, height and
* max pixels.
*/
String fileType = readImage.next() ;
int width = readImage.nextInt() ;
int height = readImage.nextInt() ;
int maxPixels = readImage.nextInt() ;

/**
* I intialise an array to read in the values of the image and use a loop to set the
* values.
*/
int[][] image = new int[height][width] ;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
image[i][j] = readImage.nextInt() ;

}
}

/**
* I re-write out the image type, width, height and max pixels.
*/
readImage.close() ;
newImage.write(fileType + "\n") ;
newImage.write(width / 2 + " " + height / 2 + "\n") ;
newImage.write(maxPixels + "\n") ;

/**
* Loop over the array, calculate the average pixel and print
*/
byte counter = 0 ;
for (int i = 1; i < height; i += 2)
{
for (int j = 1; j < width; j += 2)
{
int temp0 = image[i - 1][j - 1] ;
int temp1 = image[i - 1][j] ;
int temp2 = image[i][j - 1] ;
int temp3 = image[i][j] ;

int average = ((temp0 + temp1 + temp2 + temp3) / 4) ;
newImage.write(average + " ") ;
counter++ ;
if (counter == 17)
{
newImage.write("\n") ;
counter = 0 ;
}
}
}
// close the write and image
newImage.write("\n") ;
newImage.close() ;
}

/**
* Catch statements to catch File and IO exceptions
*/
catch (FileNotFoundException e1)
{
System.out.println("File not found!") ;
} catch (IOException e2)
{
System.out.println("File not found!") ;
}
}

最佳答案

您混淆了宽度和高度。在 PNM 格式中,像素逐行出现,height 为行数,width 为每行的长度。您正在读取数字,就好像 height 是每行的长度并且有 width 行。在写出新像素时,您也会犯同样的错误。当我用更正后的代码测试你的代码时,它似乎工作得很好。

当您的 counter 达到 15 时,您将写入 '\n',而不是在到达行的实际末尾时写入换行符。这似乎是一个不自然的打破界限的地方,但如果你喜欢这样,那么它应该不是一个真正的问题。

关于java - 查找并打印多维数组中值的平方的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20011460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com