Skip to content
Snippets Groups Projects
Commit 5ed135d3 authored by Walt Mankowski's avatar Walt Mankowski
Browse files

ImageJ distance map using OpenCV java bindings

parent 3a1dac2a
Branches
No related tags found
No related merge requests found
Pipeline #
File added
import ij.*;
import ij.plugin.filter.PlugInFilter;
import ij.process.*;
import java.awt.*;
import java.awt.image.*;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.imgproc.Imgproc;
public class Dist_OpenCV implements PlugInFilter {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public int setup(String arg, ImagePlus imp) {
if (IJ.versionLessThan("1.37j"))
return DONE;
else
return DOES_ALL+DOES_STACKS+SUPPORTS_MASKING;
}
public void run(ImageProcessor ip) {
ImageProcessor ipOut = ip.duplicate();
Mat ipMat = ip2mat(ip);
Mat ipDist = DistTransform(ipMat);
Rectangle r = ip.getRoi();
// int pad = r.height % 2;
int pad = 0;
for (int y=r.y; y<(r.y+r.height); y++) {
for (int x=r.x; x<(r.x+r.width); x++) {
try {
double[] val = ipDist.get(y, x);
ipOut.set(x, y, (int) Math.round(val[0]));
} catch (IndexOutOfBoundsException e) {
IJ.log(String.format("exception! idx = %d, x = %d, y = %d, pad = %d", x + y*r.width + y * pad, x, y, pad));
throw e;
}
}
}
new ImagePlus("Distance Transform", ipOut).show();
}
private Mat ip2mat(ImageProcessor src) {
BufferedImage bi = src.getBufferedImage();
return bufferedImageToMat(bi);
}
public Mat bufferedImageToMat(BufferedImage bi) {
Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8U);
byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
mat.put(0, 0, data);
return mat;
}
private Mat DistTransform(Mat matIn) {
Mat matOut = new Mat(matIn.size(), CvType.CV_32F);
Imgproc.distanceTransform(matIn, matOut, Imgproc.CV_DIST_L2, 3);
return matOut;
}
public BufferedImage matToBufferedImage(Mat matrix) {
int cols = matrix.cols();
int rows = matrix.rows();
int elemSize = (int)matrix.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for(int i=0; i<data.length; i=i+3) {
b = data[i];
data[i] = data[i+2];
data[i+2] = b;
}
break;
default:
return null;
}
BufferedImage image = new BufferedImage(cols, rows, type);
image.getRaster().setDataElements(0, 0, cols, rows, data);
return image;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment