2014-09-10 38 views
1

我想自己實現Sobel過濾器(實際上沒有美麗的實現)。但是在完成卷積之後,我不知道如何計算rgb值。在Java中實現Sobel過濾器 - 規範化值

  • 假設:灰色縮放後的圖像

    double [][] sobel_x = 
    { 
        { -1, 0, 1}, 
        { -2, 0, 2}, 
        { -1, 0, 1} 
    }; 
    
    double [][] sobel_y = 
    { 
        { 1, 2, 1}, 
        { 0, 0, 0}, 
        {-1, -2, 1} 
    }; 
    
    for(int y=1; y<image.getHeight()-1; y++) 
    { 
        for(int x=1; x<image.getWidth()-1; x++) 
        { 
         Color a = new Color(image.getRGB(x-1, y-1)); 
         Color b = new Color(image.getRGB(x, y-1)); 
         Color c = new Color(image.getRGB(x+1, y-1)); 
         Color d = new Color(image.getRGB(x-1, y)); 
         Color e = new Color(image.getRGB(x, y)); 
         Color f = new Color(image.getRGB(x+1, y)); 
         Color g = new Color(image.getRGB(x-1, y+1)); 
         Color h = new Color(image.getRGB(x, y+1)); 
         Color i = new Color(image.getRGB(x+1, y+1)); 
    
         double pixel_x = (sobel_x[0][0] * a.getRed()) + (sobel_x[0][1] * b.getRed()) + (sobel_x[0][2] * c.getRed()) + 
              (sobel_x[1][0] * d.getRed()) + (sobel_x[1][1] * e.getRed()) + (sobel_x[1][2] * f.getRed()) + 
              (sobel_x[2][0] * g.getRed()) + (sobel_x[2][1] * h.getRed()) + (sobel_x[2][2] * i.getRed()); 
         double pixel_y = 
              (sobel_y[0][0] * a.getRed()) + (sobel_x[0][1] * b.getRed()) + (sobel_x[0][2] * c.getRed()) + 
              (sobel_y[1][0] * d.getRed()) + (sobel_x[1][1] * e.getRed()) + (sobel_x[1][2] * f.getRed()) + 
              (sobel_y[2][0] * g.getRed()) + (sobel_x[2][1] * h.getRed()) + (sobel_x[2][2] * i.getRed()); 
    
         //Here it is possible to get values between [-1020, 1020]  
    
         //How to going on 
    
         //int rgb = (int) Math.sqrt(pixel_x*pixel_x+pixel_y*pixel_y); 
    
         //int rgbAsInt = (int)(65536 * rgb + 256 * rgb + rgb);  
        } 
    } 
    

回答

0

我的一個想法是做線性變換。例如,您獲得的圖像中的最小像素值爲-998,最大值爲1000.因此,您可以將-998與0和1000至255對應,然後獲得(-998,1000)的比例與(0,255)的比例,並將[-998,1000]至[0,255]之間的所有值歸一化。

0

下面的圖像區域具有1 x軸梯度:

1 2 3 
1 2 3 
1 2 3 

應用這種濾波器它 -

-1 0 1 
-2 0 2 
-1 0 1 

- 給出8.一個結果So X和Y梯度按比例縮放。

您需要決定什麼是您想要在輸出圖像中表示的最大梯度;稱之爲「gr_max」。 X和Y梯度應鎖定到該值:

float gr_x, gr_y, gr_max = 16; 

gr_x /= (gr_max * 8); 
gr_y /= (gr_max * 8); 

if (gr_x > 1) 
    gr_x = 1; 
if (gr_x < -1) 
    gr_x = -1; 

if (gr_y > 1) 
    gr_y = 1; 
if (gr_y < -1) 
    gr_y = -1; 

然後,假設你想在區間[0,255]你的輸出RGB值 -

int pixel_x = lround((gr_x + 1) * 255/2), 
    pixel_y = lround((gr_y + 1) * 255/2);