在图像上的像素之间插值

时间:2016-12-30 06:49:50

标签: java image-processing interpolation

我正在尝试实现一种在Java中对纹理进行采样的方法。我希望它的工作方式与使用GLSL的“纹理”功能相同。我希望在计算颜色时考虑相邻的像素。

例如,假设我使用浮点数来获取某个像素的图像颜色,并且数字介于两个像素之间。如何计算相邻像素的混合?这是显示我的目标的图像。

enter image description here

enter image description here

使用java的BufferedImage类有一种简单的方法吗?

这是我到目前为止的代码,它目前仅适用于x位置。

public static final java.awt.Color getColor(final BufferedImage image, final float x, final int y) {

    final float imageX = x * image.getWidth();

    final float decimal = imageX % 1f;

    final java.awt.Color left = new java.awt.Color(image.getRGB(Maths.clamp((int) imageX - 1, 0, image.getWidth() - 1), y));
    final java.awt.Color center = new java.awt.Color(image.getRGB(Maths.clamp((int) imageX, 0, image.getWidth() - 1), y));
    final java.awt.Color right = new java.awt.Color(image.getRGB(Maths.clamp((int) imageX + 1, 0, image.getWidth() - 1), y));

    if (decimal == 0.5f) return center;

    if (decimal < 0.5f) {

        final float distanceFromCenter = 0.5f - decimal;
        final float distanceFromLeft = decimal + 0.5f;

        final Vector3f leftColor = new Vector3f(left.getRed() / 255f, left.getGreen() / 255f, left.getBlue() / 255f);
        final Vector3f centerColor = new Vector3f(center.getRed() / 255f, center.getGreen() / 255f, center.getBlue() / 255f);

        leftColor.scale(1f - distanceFromLeft);
        centerColor.scale(1f - distanceFromCenter);

        final Vector3f color = Vector3f.add(leftColor, centerColor, null);

        return new java.awt.Color(color.getX(), color.getY(), color.getZ());

    } else {

        final float distanceFromCenter = decimal - 0.5f;
        final float distanceFromRight = 1f - decimal + 0.5f;

        final Vector3f rightColor = new Vector3f(right.getRed() / 255f, right.getGreen() / 255f, right.getBlue() / 255f);
        final Vector3f centerColor = new Vector3f(center.getRed() / 255f, center.getGreen() / 255f, center.getBlue() / 255f);

        rightColor.scale(1f - distanceFromRight);
        centerColor.scale(1f - distanceFromCenter);

        final Vector3f color = Vector3f.add(rightColor, centerColor, null);

        return new java.awt.Color(color.getX(), color.getY(), color.getZ());

    }

}

1 个答案:

答案 0 :(得分:0)

希望此代码有所帮助,如果你恰当地使用它。此函数从缓冲图像中提取像素,我们可以根据需要替换它:

    private BufferedImage changeColor(BufferedImage image, int srcColor, int replaceColor)
{

    BufferedImage destImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = destImage.createGraphics();
    g.drawImage(image, null, 0, 0);
    g.dispose();


    for (int width = 0; width < image.getWidth(); width++)
    {
        for (int height = 0; height < image.getHeight(); height++)
        {

           if (destImage.getRGB(width, height) == srcColor)
            {
               destImage.setRGB(width, height, replaceColor);
            }

        }
    }

    return destImage;
}