我一直遇到一个非常简单的问题,但由于某种原因我似乎无法解决问题,但我觉得我很接近。我想知道我有多远/接近以及我可以进入的方向。
基本上,我将图像作为pnm文件接收,并将像素值输入到2d数组中。然后,我必须采用4像素的正方形,找到平均值,然后将其打印到新文件,有效地使图像变小。
例如一个包含4个像素的正方形:
0 10
12 14
变成一个值:9
主要关注的是我计算平均值的循环。我增加2,因为我只想看一个正方形的值。我访问4个像素的索引并用它们初始化临时变量,并找到我写入输出文件的平均值。
不幸的是,我似乎没有得到平均值,而且正在打印的图像是完全错误的。任何帮助将不胜感激,谢谢!
主编辑。好的,每个人给予我的帮助,我似乎已经解决了这个问题。这些问题不是通过计算平均像素而产生的,而是随着2d阵列的初始化而产生的。当我声明所以我正在拍摄并使用错误的像素来计算时,我混淆了两个宽度和高度像素值。在最终版本中,代码在修复时适用于任何大小的图片。感谢大家的帮助,特别是@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!") ;
}
}
答案 0 :(得分:0)
你的宽度和高度混淆了。在PNM格式中,像素逐行排列,行数为height
,每行的长度为width
。您正在读取数字,好像height
是每行的长度,并且有width
行。在写出新像素时,你也犯了同样的错误。当我用纠正的代码测试你的代码时,它似乎完美无缺。
当'\n'
到达15时,您正在写counter
,而不是在到达行的实际末尾时写入换行符。这似乎是一个不自然的地方,打破线条,但如果你喜欢这样,那么它应该不是一个真正的问题。
答案 1 :(得分:0)
您的代码似乎适用于方形.pnm文件。我使用以下pnm来测试
P2
10 10
255
254 254 254 254 252 210 147 109 108 135 143 143 140 140 146 137 135
134 132 133 131 131 129 130 128 129 127 129 126 127 135 109 55 94
152 110 92 138 145 163 163 163 160 162 163 168 164 163 165 163 164
162 167 162 162 161 160 159 162 161 159 161 162 162 161 159 166 163
168 180 77 127 170 164 159 159 158 156 157 159 157 157 159 158 157
157 158 158 161 161 161 167 166 166 177 176 180 176 173 173
运行它生成的代码:
P2
5 5
255
198 197 186 131 127 126 102 129 121 140 163 162 163 161 162
131 164 159 160 166 160 162 166 168 167
第一个方格是:
254 254
143 143
average = 198.5,其中 - &gt; 198,因为您使用int
来存储值。请注意,文件的每一行中有17个条目,因此文件第一行中的11/12条目实际上是第二行中的前2个值。希望有意义