2012-04-14 2 views
2

Я пытаюсь создать гуасианский фильтр, не используя ConvolveOp. У меня много проблем, пытаясь заставить это работать, я получил фильтр с серой шкалой, но для этого у меня проблемы с поиском расположения пикселов 8 соседей, поэтому я могу применить фильтр. вот что я до сих пор. Это правильный способ приблизиться к каждому пикселю?Гауссовский фильтр без использования ConvolveOp

public class Gaussian implements Filter { 


    public void filter(PixelImage pi) { 
    Pixel[][] data = pi.getData(); 
    Pixel[][] original = data; 


    int kernel_rows = 3; 
    int kernel_cols = 3; 

    // define kernel here (double loop), these are the 1/16, 2/16, etc... 
    // values that you're multiplying the image pixels by 
    double[][] kernel = {{1,2,1}, 
     {2,4,2}, 
     {1,2,1}}; 

    // iterate over each pixel in the image 
    for (int row = 0; row < pi.getHeight(); row ++) { 
     for (int col = 0; col < pi.getWidth(); col++) { 
     // iterate over each pixel in the kernel 
     for (int row_offset = 0 ; row_offset < kernel_rows ; row_offset++) { 
      for (int col_offset = 0 ; col_offset < kernel_cols ; col_offset++) { 

      // subtract by half the kernel size to center the kernel 
      // on the pixel in question 
      // ** you'll have to modify to account for boundary conditions ** 
      int row_index = row + row_offset - kernel_rows/2; 
      int col_index = col + col_offset - kernel_cols/2; 

      int r =0; 
      int g =0; 
      int b =0; 




      r += (data[row_index][col_index].red * kernel[row_offset][col_offset])/16; 
      g += (data[row_index][col_index].green * kernel[row_offset][col_offset])/16; 
      b += (data[row_index][col_index].blue * kernel[row_offset][col_offset])/16; 
      Pixel temp =new Pixel(r, g, b); 
      original[row][col] = temp; 
      } 
     } 
     data = original; 
     pi.setData(data); 

     } 
    } 
    } 
} 

ответ

4

Свертка является по существу в четыре раза вложенного цикла: два цикла через пикселей в изображении, и, в каждом пикселе, два цикла по пикселям в ядре.

Таким образом, вы можете очистить ваш код значительно с чем-то вроде этого:

int kernel_rows = 3; 
    int kernel_cols = 3; 

    // define kernel here (double loop), these are the 1/16, 2/16, etc... 
    // values that you're multiplying the image pixels by 
    double[][] kernel = ... 

    // iterate over each pixel in the image 
    // leave a kernel_rows/2 sized gap around the edge of the image 
    // so that we don't run into IndexOutOfBounds exceptions 
    // when performing the convolution 
    for (int row = kernel_rows/2; row < pi.getHeight() - kernel_rows/2; row ++) { 
    for (int col = kernel_cols/2; col < pi.getWidth() - kernel_cols/2; col++) { 

     int r = 0; 
     int g = 0; 
     int b = 0; 

     // iterate over each pixel in the kernel 
     for (int row_offset = 0 ; row_offset < kernel_rows ; row_offset++) { 
     for (int col_offset = 0 ; col_offset < kernel_cols ; col_offset++) { 

      // subtract by half the kernel size to center the kernel 
      // on the pixel in question 
      int row_index = row + row_offset - kernel_row/2; 
      int col_index = col + col_offset - kernel_cols/2 

      r += data[row_index][col_index].red * kernel[row_offset][col_offset]; 
      g += data[row_index][col_index].green * kernel[row_offset][col_offset]; 
      b += data[row_index][col_index].blue * kernel[row_offset][col_offset]; 

     } 
     } 

    data[row][col] = new Pixel(r, g, b); 

    } 
    } 
+0

Ok так я редактировал код, указанный выше. Я получаю ошибку, что r, g, b не инициализируются. Я попытался положить их перед петлями и даже дал ему нулевое значение изначально. Но я все еще не инициализирую r. –

+0

Вам придется инициализировать их все отдельно (отредактированный код выше). – ulmangt

+0

Итак, я думаю, что получил это, но я все еще получаю исключение из-за пределов. Правильно ли настроен мой массив ядра? Я знаю, что остальная часть моего кода хороша, потому что я могу заставить другие фильтры работать. Большое вам спасибо за помощь в этом! Я редактировал мой код выше. –