【问题标题】:negative values in the writableraster可写光栅中的负值
【发布时间】:2014-10-26 16:36:18
【问题描述】:

我正在尝试实现具有不同尺寸 3x3 、 5x5 、 7x7 和 11x11 的平均滤波器。我进行了计算,调试时结果是正确的,但问题是它以负数保存在可写栅格中,所以我得到了奇怪的结果。第二个奇怪的事情是,当我想获取以负值保存的同一像素的值时,它以正值检索! 我正在使用 int。 怎么了?有什么帮助吗?!!

这是我的 5x5 平均滤波器代码。

   public static BufferedImage filter5x5_2D(BufferedImage paddedBI , BufferedImage bi , double[][]filter)
{

    WritableRaster myImage = paddedBI.copyData(null);
    BufferedImage img = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    WritableRaster myImage2 = img.copyData(null);

    for(int i =2; i< myImage.getHeight()-2; i++)
        {
            for(int j =2; j< myImage.getWidth()-2; j++)
            {
                int value = 0;
                int copyi = i-2;
                for (int m = 0 ; m<5 ;  m++)
                {   
                    int copyj = j-2;
                    for (int n = 0; n<5; n++)
                    {
                        int result = myImage.getSample(copyj , copyi, 0);
                        double f = filter[m][n];
                        double add = result * filter[m][n];
                        value += (int) (filter[m][n] * myImage.getSample(copyj , copyi, 0));    
                        copyj ++;
                    }
                    copyi++;
                    //myImage2.setSample(j-1 , i-1, 0, value);
                }

                myImage2.setSample(j-2 , i-2, 0, value);
                //int checkResult = myImage2.getSample(j-1,i-1,0);
            }       
        }
    BufferedImage res= new BufferedImage(bi.getWidth(),bi.getHeight(),BufferedImage.TYPE_BYTE_GRAY);
    res.setData(myImage2);
    return res;
}

【问题讨论】:

  • Java bytes(与所有 Java 整数类型一样)已签名。使用TYPE_BYTE_GRAY,您将获得byte 值,范围为-128...127。用 byteValue &amp; 0xff 屏蔽符号,使其值在 0...255 范围内。

标签: java image-processing bufferedimage raster


【解决方案1】:

我没有发现任何负值。这是我测试此代码的主要内容:

public static void main(String[] args) throws IOException {
    BufferedImage bi = ImageIO.read(new File("C:/Tmp/test.bmp")); 

    BufferedImage newImage = new BufferedImage(bi.getWidth()+4, bi.getHeight()+4, bi.getType());

    Graphics g = newImage.getGraphics();

    g.setColor(Color.white);
    g.fillRect(0,0,bi.getWidth()+4,bi.getHeight()+4);
    g.drawImage(bi, 2, 2, null);
    g.dispose();

    double[][] filter = new double[5][5];
    for( int i = 0; i < 5; ++i){
        for( int j = 0; j < 5; ++j){
            filter[i][j] = 1.0/(5*5);
        }
    }
    BufferedImage filtered = filter5x5_2D(newImage, bi, filter);
    ImageIO.write(filtered, "bmp", new File("C:/tmp/filtered.bmp"));
}

您应该考虑到您的变量resultfadd 未使用。如果value 的类型是double 而不是int,那会更好。在最坏的情况下,你会得到 11 的 25 倍,乘以 1/25 后将四舍五入为零。这将导致您的代码的灰度值为零,而它应该导致 11。

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2016-02-18
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2020-10-02
    • 2019-04-22
    相关资源
    最近更新 更多