java - 为什么图片是黑色的?
问题描述
编写一个方法 Picture emboss,通过应用以下内核为图片添加浮雕风格效果。
| -2 -1 0 |
| -1 1 1 |
| 0 1 2 |
(它是一个 3*3 矩阵)
当对边界附近的像素应用内核过滤器时,它的某些相邻像素可能不存在。在这种情况下,假设最左边的列环绕到最右边的列,反之亦然;顶行环绕到底行,反之亦然。
下面是我的代码的一部分,但我发现我得到的图片全是黑色的。我对java的了解有限。所以检查了一段时间后,我仍然找不到错误。
public static Picture emboss(Picture picture) {
int width= picture.width();
int height= picture.height();
int[][] matrix1 = new int[height][width];
int[][] matrix2 = new int[height][width];
int[][] matrix3 = new int[height][width];
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++){
Color color = picture.getColor(col, row);
matrix1[row][col] = color.getRed();
matrix2[row][col] = color.getGreen();
matrix3[row][col] = color.getBlue();
int a = row-1;
int b = col-1;
int c = row+1;
int d = col+1;
if (a < 0) {
a = height-1;
}
if (b < 0) {
b = width-1;
}
if (c > height-1) {
c = 0;
}
if ( d > width-1 ) {
d = 0;
}
int GR = -2 * matrix1[a][b] - matrix1[row][b] - matrix1[a][col] + matrix1[row][col] + matrix1[c][col] + matrix1[row][d] + 2*matrix1[c][d];
int GG = -2 * matrix2[a][b] - matrix2[row][b] - matrix2[a][col] + matrix2[row][col] + matrix2[c][col] + matrix2[row][d] + 2*matrix2[c][d];
int GB = -2 * matrix3[a][b] - matrix3[row][b] - matrix3[a][col] + matrix3[row][col] + matrix3[c][col] + matrix3[row][d] + 2*matrix3[c][d];
if (GR < 0) {
GR=0;
}
if( GR>255 ) {
GR=255;
}
if ( GG<0 ) {
GG=0;
}
if( GG>255 ) {
GG=255;
}
if ( GB<0 ) {
GB=0;
}
if ( GB>255 ) {
GB=255;
}
Color newColor= new Color(GR,GG,GB);
picture.setColor(col,row,newColor);
}
}
return picture;
}
解决方案
当您创建这样的矩阵时
int[][] matrix1 = new int[height][width];
默认情况下用 0 填充。
看看你什么时候给矩阵一个值。在 for 循环的第一次迭代中,一切都是黑色的。您首先设置当前像素:
matrix1[row][col] = color.getRed();
但是所有的邻居仍然是黑人。当您在迭代中移动时,所有尚未计算的像素都是黑色的,并且您在使用邻居时将它们包括在计算中。
您应该首先进行一次迭代以填充这三个矩阵,然后进行另一次迭代以进行计算:
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++){
Color color = picture.getColor(col, row);
matrix1[row][col] = color.getRed();
matrix2[row][col] = color.getGreen();
matrix3[row][col] = color.getBlue();
}
}
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++){
int a = row-1;
int b = col-1;
[...] // The rest of the code goes here
}
}
推荐阅读
- c++ - C/C++ 位域字节序在实际实践中真的是个问题吗?
- spring-cloud-contract - 与第三方或非 Java 应用程序的 Spring 合同
- r - theta 分量的数量不正确 (!1)
- r - 如何基于组而不是组内创建重复索引
- java - 在pdfBox之后我无法删除文件
- ios - 如果存在则调用特定函数,否则默认来自协议
- android - What, exactly, does Android DatePicker.setMinDate() and DatePicker.setMaxDate() do?
- c - 我遇到了“缓冲区溢出数组索引超出范围”错误
- angular - 我想在 ngOnInit() { } 的第二个方法中使用 .subscribe 的结果
- git - 推送到 Github 失败,因为它找不到 LFS 文件?