|
| 1 | +package org.knime.knip.dl4j.data.convert; |
| 2 | + |
| 3 | +import java.util.Iterator; |
| 4 | + |
| 5 | +import org.knime.ext.dl4j.base.data.convert.extension.BaseDL4JConverter; |
| 6 | +import org.knime.knip.base.data.img.ImgPlusValue; |
| 7 | + |
| 8 | +import net.imglib2.img.Img; |
| 9 | +import net.imglib2.type.numeric.RealType; |
| 10 | + |
| 11 | +/** |
| 12 | + * DL4JConverter that converts a ImgPlusValue to double[]. |
| 13 | + * |
| 14 | + * @author David Kolb, KNIME.com GmbH |
| 15 | + * |
| 16 | + * @param <T> |
| 17 | + */ |
| 18 | +@SuppressWarnings("rawtypes") |
| 19 | +public class ImgPlusValueToDoubleArrayConverter<T extends RealType<T>> |
| 20 | + extends BaseDL4JConverter<ImgPlusValue, double[]> { |
| 21 | + |
| 22 | + /** |
| 23 | + * Constructor for class ImgPlusValueToDoubleArrayConverter. |
| 24 | + */ |
| 25 | + public ImgPlusValueToDoubleArrayConverter() { |
| 26 | + super(ImgPlusValue.class, double[].class, BaseDL4JConverter.DEFAULT_PRIORITY); |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * {@inheritDoc} Flattens the image and copies the pixel values to double[]. |
| 31 | + */ |
| 32 | + @Override |
| 33 | + @SuppressWarnings("unchecked") |
| 34 | + public double[] convert(ImgPlusValue source) throws Exception { |
| 35 | + Img<T> img = source.getImgPlus(); |
| 36 | + Iterator<T> imgIter = img.iterator(); |
| 37 | + double[] flattenedImg = new double[(int) calcNumPixels(source.getDimensions())]; |
| 38 | + int i = 0; |
| 39 | + while (imgIter.hasNext()) { |
| 40 | + flattenedImg[i] = imgIter.next().getRealDouble(); |
| 41 | + i++; |
| 42 | + } |
| 43 | + return flattenedImg; |
| 44 | + } |
| 45 | + |
| 46 | + private long calcNumPixels(long[] dims) { |
| 47 | + long numPix = 1; |
| 48 | + for (long dim : dims) { |
| 49 | + numPix *= dim; |
| 50 | + } |
| 51 | + return numPix; |
| 52 | + } |
| 53 | + |
| 54 | +} |
0 commit comments