2014-09-10 40 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);