Reputation: 174
I have implemented a convolution filter in java. I did this a while back in ap cs but now I actually need it for something, so I re implemented it to make sure I still know how to do it. Unfortunately I lost my working copy so I can't compare current code to my previous working code. I am pretty sure I am implementing the algorithm correctly, but the code is still not working properly. Can an experienced programmer please explain what I am doing wrong.
Here is the Convolution class:
import java.awt.*;
import java.util.Arrays;
public class ConvolutionFilter {
private int[][] image;
private int[][] weights;
private double[][] doubleWeights;
private int[][] convolved;
public ConvolutionFilter(int[][] image, int[][] weights) {
this.image = image;
this.weights = weights;
convolve();
}
public void convolve() {
int sum;
int[][] convolved = new int[image.length][image[0].length];
for (int r = 0; r < convolved.length - weights.length - 1; r++) {
for (int c = 0; c < convolved[r].length - weights.length - 1; c++) {
sum = 0;
for (int i = 0; i < weights.length; i++) {
for (int j = 0; j < weights[i].length; j++) {
sum += image[r + i][c + j] * weights[i][j];
}
}
convolved[r][c] = sum / weight();
}
}
this.convolved = convolved;
}
public int numWeights() {
return weights.length * weights[0].length;
}
public int weight() {
int sum = 0;
for (int r = 0; r < weights.length; r++) {
for (int c = 0; c < weights[r].length; c++) {
sum += weights[r][c];
}
}
if (sum == 0) return 1; else return sum;
}
public int[][] getConvolved() {
return convolved;
}
}
Any help is appreciated!
Upvotes: 2
Views: 191
Reputation: 64904
To adapt this to RGB, the arithmetic should be done per channel instead of over the packed representation, for example (not tested)
public void convolve() {
int[][] convolved = new int[image.length][image[0].length];
double invScale = 1.0 / weight();
for (int r = 0; r < convolved.length - weights.length - 1; r++) {
for (int c = 0; c < convolved[r].length - weights.length - 1; c++) {
int rsum = 0, gsum = 0, bsum = 0;
for (int i = 0; i < weights.length; i++) {
for (int j = 0; j < weights[i].length; j++) {
int pixel = image[r + i][c + j];
int w = weights[i][j];
rsum += ((pixel >> 16) & 0xFF) * w;
gsum += ((pixel >> 8) & 0xFF) * w;
bsum += (pixel & 0xFF) * w;
}
}
rsum = (int)(rsum * invScale);
gsum = (int)(gsum * invScale);
bsum = (int)(bsum * invScale);
convolved[r][c] = bsum | (gsum << 8) | (rsum << 16) | (0xFF << 24);
}
}
this.convolved = convolved;
}
Upvotes: 1