I'm trying to code a simple image processing library using a few simple kernel filters for applying effects like- gaussian, sharpen, motion blur, etc. to images using java. The kernels are mostly 3x3 matrix but only in the case of motion blur it is a 9x9 matrix. To apply a kernel filter to an image, I have to perform the following operation for each pixel p:
-->Align the center of the kernel on pixel p.
-->The new value of pixel p is obtained by multiplying each kernel element with the corresponding RGB values of the pixels, and adding the results and setting it to the center pixel p. I have almost completed coding the image processing library. However, when I run the program, the image appears blank. I have used a private helper function that takes any arbitrary kernel filter and applies the same on the image. Here is my code-
import java.awt.Color;
public class KernelFilter {
// Returns a new picture that applies an arbitrary kernel filter to the given picture.
private static Picture kernel(Picture picture, double[][] weights) {
int width = picture.width();
int height = picture.height();
Picture pic = new Picture(width, height);
double r = 0, g = 0, b = 0;
int a, c, d;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int n = weights.length;
int mid = n / 2;
for (int k = 0; k < n; k++) {
for (int l = 0; l < n; l++) {
int pr = (i + (k - mid)) % n;
int pc = (j + (l - mid)) % n;
if (pr < 0) pr += n;
if (pc < 0) pc += n;
Color color = picture.get(pr, pc);
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
r += red * weights[k][l];
g += green * weights[k][l];
b += blue * weights[k][l];
}
}
a = (int) Math.round(r);
c = (int) Math.round(g);
d = (int) Math.round(b);
if (a > 255) a = 255;
if (a < 0) a = 0;
if (c > 255) c = 255;
if (c < 0) c = 0;
if (d > 255) d = 255;
if (d < 0) d = 0;
Color col = new Color(a, c, d);
pic.set(i, j, col);
}
}
return pic;
}
public static Picture gaussian(Picture picture) {
double[][] gaussian = {
{ 1 / 16, 2 / 16, 1 / 16 }, { 2 / 16, 4 / 16, 2 / 16 },
{ 1 / 16, 2 / 16, 1 / 16 }
};
return kernel(picture, gaussian);
}
// Test client (ungraded).
public static void main(String[] args) {
Picture pic = new Picture(args[0]);
Picture pic2 = gaussian(pic);
pic2.show();
}
}
Something is wrong and I'm not able to figure it out, would be really grateful if someone pointed out my mistake. Thanks!
Aucun commentaire:
Enregistrer un commentaire