图像内核过滤器不能产生正确的结果

时间:2015-04-09 14:26:45

标签: java imagefilter

我编写了一些代码来改变图像内核过滤器的尺寸。您可以选择3x3,5x5或7x7矩阵。问题是当我切换到5x5或7x7时,只有前3行和3列中的单元有效。所以它们就像一个3x3矩阵。我如何知道它不起作用的一个例子是当我尝试使用5x5或7x7应用单位矩阵时,除了中心单元格外,我将在零处有零,这将有一个。对我来说,这会产生黑色图像。

以下是应用图像内核的代码

for (int y = 1; y < img.height-1; y++) {   // Skip top and bottom edges
    for (int x = 1; x < img.width-1; x++) {  // Skip left and right edges
          float sumR = 0; // Kernel sum for this pixel
          float sumG = 0; 
          float sumB = 0; 
      for (int ky = -1; ky <= 1; ky++) {
        for (int kx = -1; kx <= 1; kx++) {
          // Calculate the adjacent pixel for this kernel point
          int pos = (y + ky)*img.width + (x + kx);
          float rVal = red(img.pixels[pos]);
          float gVal = green(img.pixels[pos]);
          float bVal = blue(img.pixels[pos]);
          // Multiply adjacent pixels based on the kernel values
          sumR += kernel[ky+1][kx+1] * rVal;
          sumG += kernel[ky+1][kx+1] * gVal;
          sumB += kernel[ky+1][kx+1] * bVal; 
        }
      }
      //For this pixel in the new image, set the rgb value
      //based on the sum from the kernel
      edgeImg.pixels[y*img.width + x] = color(sumR,sumG,sumB);
    }
  }

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望将此代码用于5x5和7x7内核。

如果是这样,问题是这样的:

for (int ky = -1; ky <= 1; ky++) {
for (int kx = -1; kx <= 1; kx++) {

因为它总是会循环3次。

假设内核大小存储在变量kernel_size中,可能是新代码:

// Calculate the distance from the center to the edge
int side_width = (kernel_size-1)/2

for (int y = side_width; y < img.height-side_width; y++) {   // Skip top and bottom edges
    for (int x = side_width; x < img.width-side_width; x++) {  // Skip left and right edges
      float sumR = 0; // Kernel sum for this pixel
      float sumG = 0; 
      float sumB = 0; 

for (int ky = 0; ky <= kernel_size - 1; ky++) {
    for (int kx = 0; kx <= kernel_size - 1; kx++) {
        // Calculate the adjacent pixel for this kernel point
        int pos = (y - side_width + ky)*img.width + (x - side_width + kx);
        float rVal = red(img.pixels[pos]);
        float gVal = green(img.pixels[pos]);
        float bVal = blue(img.pixels[pos]);
        // Multiply adjacent pixels based on the kernel values
        sumR += kernel[ky][kx] * rVal;
        sumG += kernel[ky][kx] * gVal;
        sumB += kernel[ky][kx] * bVal; 
    }
}

  //For this pixel in the new image, set the rgb value
  //based on the sum from the kernel
  edgeImg.pixels[y*img.width + x] = color(sumR,sumG,sumB);
}

}

我没有测试过这段代码,但这个想法应该很明确。