Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save joshuamzm/264b498878dbd663942e to your computer and use it in GitHub Desktop.

Select an option

Save joshuamzm/264b498878dbd663942e to your computer and use it in GitHub Desktop.
/** Convolves the float image <code>ip</code> with a kernel of width
<code>kw</code> and height <code>kh</code>. Returns false if
the user cancels the operation by pressing 'Esc'. */
public boolean convolveFloat(ImageProcessor ip, float[] kernel, int kw, int kh) {
if (!(ip instanceof FloatProcessor))
throw new IllegalArgumentException("FloatProcessor required");
if (canceled) return false;
int width = ip.getWidth();
int height = ip.getHeight();
Rectangle r = ip.getRoi();
int x1 = r.x;
int y1 = r.y;
int x2 = x1 + r.width;
int y2 = y1 + r.height;
int uc = kw/2;
int vc = kh/2;
float[] pixels = (float[])ip.getPixels();
float[] pixels2 = (float[])ip.getSnapshotPixels();
if (pixels2==null)
pixels2 = (float[])ip.getPixelsCopy();
double scale = normalize?getScale(kernel):1.0;
Thread thread = Thread.currentThread();
boolean isMainThread = thread==mainThread || thread.getName().indexOf("Preview")!=-1;
if (isMainThread) pass++;
double sum;
int offset, i;
boolean edgePixel;
int xedge = width-uc;
int yedge = height-vc;
long lastTime = System.currentTimeMillis();
for (int y=y1; y<y2; y++) {
long time = System.currentTimeMillis();
if (time-lastTime>100) {
lastTime = time;
if (thread.isInterrupted()) return false;
if (isMainThread) {
if (IJ.escapePressed()) {
canceled = true;
ip.reset();
ImageProcessor originalIp = imp.getProcessor();
if (originalIp.getNChannels() > 1)
originalIp.reset();
return false;
}
showProgress((y-y1)/(double)(y2-y1));
}
}
for (int x=x1; x<x2; x++) {
if (canceled) return false;
sum = 0.0;
i = 0;
edgePixel = y<vc || y>=yedge || x<uc || x>=xedge;
for (int v=-vc; v <= vc; v++) {
offset = x+(y+v)*width;
for(int u = -uc; u <= uc; u++) {
if (edgePixel) {
if (i>=kernel.length) // work around for JIT compiler bug on Linux
IJ.log("kernel index error: "+i);
sum += getPixel(x+u, y+v, pixels2, width, height)*kernel[i++];
} else
sum += pixels2[offset+u]*kernel[i++];
}
}
pixels[x+y*width] = (float)(sum*scale);
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment