Search code examples
javainterpolationweighted-average

java triangle interpolation how to aka rgb test image


So what i wanted to do is interpolate a triangle in java without any external libraries for a challenge, just using swing to display the image. I searched all over the web and i couldn't find anything. Thats why i'm making this.


Solution

  • The solution: Weighted averages!

    private int interpolate(int x, int y, int v1, int v2, int v3) {
        // these are my triangle corners
    
        Vector p1v = new Vector(p1.x, p1.y);
        Vector p2v = new Vector(p2.x, p2.y);
        Vector p3v = new Vector(p3.x, p3.y);
    
        // current point
        Vector f = new Vector(x, y);
    
        // calculate weighted average
    
        double a1 = triangleArea(f, p2v, p3v);
        double a2 = triangleArea(f, p1v, p3v);
        double a3 = triangleArea(f, p1v, p2v);
    
        return (int) ((a1 * v1 + a2 * v2 + a3 * v3) / (a1 + a2 + a3));
    
    }
    

    Usage - put in double for loop for x and y values:

    int red = interpolate((int) x, y, p1red, p2red, p3red);
    int green = interpolate((int) x, y, p1green, p2green, p3green);
    int blue = interpolate((int) x, y, p1blue, p2blue, p3blue);
    
    //System.out.println("xyrgb: " + (int)x + ", " + y + ", " + red + ", " + green + ", " + blue);
    
    bI.setRGB((int)x, y, new Color(red, green, blue).getRGB());
    

    You can find more of the code on my github: here

    Screenie: lol