Search in sources :

Example 1 with UnsignedByteType

use of net.imglib2.type.numeric.integer.UnsignedByteType in project imagej-ops by imagej.

the class InvertTest method testUnsignedByteTypeInvert.

@Test
public void testUnsignedByteTypeInvert() {
    final Img<UnsignedByteType> inUnsignedByteType = generateUnsignedByteArrayTestImg(true, 5, 5);
    final Img<UnsignedByteType> outUnsignedByteType = inUnsignedByteType.factory().create(inUnsignedByteType, new UnsignedByteType());
    assertDefaultInvert(inUnsignedByteType, outUnsignedByteType);
    assertDefaultInvertMinMaxProvided(inUnsignedByteType, outUnsignedByteType, new UnsignedByteType((byte) 127), new UnsignedByteType((byte) 127));
    assertDefaultInvertMinMaxProvided(inUnsignedByteType, outUnsignedByteType, new UnsignedByteType((byte) -12), new UnsignedByteType((byte) -10));
}
Also used : UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType) AbstractOpTest(net.imagej.ops.AbstractOpTest) Test(org.junit.Test)

Example 2 with UnsignedByteType

use of net.imglib2.type.numeric.integer.UnsignedByteType in project imagej-ops by imagej.

the class ImageMomentsTest method createImg.

@BeforeClass
public static void createImg() {
    Img<UnsignedByteType> tmp = ArrayImgs.unsignedBytes(new long[] { 100, 100 });
    Random rand = new Random(1234567890L);
    final Cursor<UnsignedByteType> cursor = tmp.cursor();
    while (cursor.hasNext()) {
        cursor.next().set(rand.nextInt((int) tmp.firstElement().getMaxValue()));
    }
    img = tmp;
}
Also used : Random(java.util.Random) UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType) BeforeClass(org.junit.BeforeClass)

Example 3 with UnsignedByteType

use of net.imglib2.type.numeric.integer.UnsignedByteType in project imagej-ops by imagej.

the class CopyArrayImgTest method createData.

@Before
public void createData() {
    input = new ArrayImgFactory<UnsignedByteType>().create(new int[] { 120, 100 }, new UnsignedByteType());
    final Random r = new Random(System.currentTimeMillis());
    final Cursor<UnsignedByteType> inc = input.cursor();
    while (inc.hasNext()) {
        inc.next().setReal(r.nextDouble() * 255);
    }
}
Also used : Random(java.util.Random) UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType) ArrayImgFactory(net.imglib2.img.array.ArrayImgFactory) Before(org.junit.Before)

Example 4 with UnsignedByteType

use of net.imglib2.type.numeric.integer.UnsignedByteType in project vcell by virtualcell.

the class SmallCR method calcMSE.

// public static IJSolverStatus runFrapSolver(VCellHelper vh,double diffusionRate,String cacheKey,VCellHelper.IJGeom overrideGeom) throws Exception{
// //Override Model/Simulation parameter values (user must have knowledge of chosen model to know what parameter names to override)
// HashMap<String,String> simulationParameterOverrides = new HashMap<>();
// simulationParameterOverrides.put("rf_diffusionRate", ""+diffusionRate);
// HashMap<String, String> speciesContextInitialConditionsOverrides = new HashMap<>();
// String laserArea = "((x >=  "+43+") && (x <= "+47+") && (y >=  "+22+") && (y <= "+26+"))";
// speciesContextInitialConditionsOverrides.put("Laser", laserArea);
// double newEndTime = 10.0;
// //Start Frap simulation
// IJSolverStatus ijSolverStatus = vh.startVCellSolver(Long.parseLong(cacheKey), overrideGeom, simulationParameterOverrides, speciesContextInitialConditionsOverrides,newEndTime);
// return ijSolverStatus;
// }
// public static String waitForSolverGetCacheForData(VCellHelper vh,IJSolverStatus ijSolverStatus) throws Exception{
// //Wait for solver to finish
// System.out.println(ijSolverStatus.toString());
// String simulationJobId = ijSolverStatus.simJobId;
// while(true) {
// Thread.sleep(5000);
// ijSolverStatus =  vh.getSolverStatus(simulationJobId);
// System.out.println(ijSolverStatus.toString());
// String statusName = ijSolverStatus.statusName.toLowerCase();
// if(statusName.equals("finished") || statusName.equals("stopped") || statusName.equals("aborted")) {
// break;
// }
// }
// return vh.getSimulationDataCacheKey(ijSolverStatus.simJobId);
// }
// public static SCIFIOImgPlus<DoubleType> zProjectNormalizeSimData(VCellHelper vh,
// String newImgPlusName,String simulationDataCachekey,String varToAnalyze,int preBleachTimeIndex,int solverStatus_jobIndex,int ANALYZE_BEGIN_TIMEINDEX,int ANALYZE_END_TIMEINDEX) throws Exception{
// 
// int ANALYZE_COUNT = ANALYZE_END_TIMEINDEX - ANALYZE_BEGIN_TIMEINDEX+1;
// // Get the SIMULATION pre-bleach timepoint data for normalizing
// VCellHelper.TimePointData timePointData = vh.getTimePointData(simulationDataCachekey, varToAnalyze, new int[] {preBleachTimeIndex}, solverStatus_jobIndex);
// int xysize = timePointData.getBasicStackDimensions().xsize*timePointData.getBasicStackDimensions().ysize;
// double[] bleachedTimeStack = new double[ANALYZE_COUNT*xysize];
// //	    checkSizes(timePointData.getBasicStackDimensions(), xsize, xysize, zsize);
// //    	URL dataUrl = new URL("http://localhost:"+vh.findVCellApiServerPort()+"/"+"getdata"+"?"+"cachekey"+"="+cachekey+"&"+"varname"+"="+varToAnalyze+"&"+"timeindex"+"="+(int)(0)+"&"+"jobid="+ijSolverStatus.getJobIndex());
// double[] zProjectedSimNormalizer = getNormalizedZProjected(timePointData,null);
// //showAndZoom(ij, "Sim Data PreBleach", ArrayImgs.doubles(simNormalizer, xsize,ysize), 4);
// 
// // Get the SIMULATION post-bleach data to analyze
// for(int timeIndex = ANALYZE_BEGIN_TIMEINDEX;timeIndex<=ANALYZE_END_TIMEINDEX;timeIndex++){
// timePointData = vh.getTimePointData(simulationDataCachekey, varToAnalyze, new int[] {timeIndex}, solverStatus_jobIndex);
// //	    	checkSizes(timePointData.getBasicStackDimensions(), xsize, xysize, zsize);
// //	    	dataUrl = new URL("http://localhost:"+vh.findVCellApiServerPort()+"/"+"getdata"+"?"+"cachekey"+"="+cachekey+"&"+"varname"+"="+varToAnalyze+"&"+"timeindex"+"="+(int)timeIndex+"&"+"jobid="+ijSolverStatus.getJobIndex());
// double[] data = getNormalizedZProjected(timePointData,zProjectedSimNormalizer);
// System.arraycopy(data, 0, bleachedTimeStack, (timeIndex-ANALYZE_BEGIN_TIMEINDEX)*xysize, data.length);
// }
// 
// //Turn VCell data into iterableinterval
// //    	FinalInterval zProjectedSimDataSize = FinalInterval.createMinSize(new long[] {0,0,0, xsize,ysize,ANALYZE_COUNT});//xyzt:origin and xyzt:size
// ArrayImg<DoubleType, DoubleArray> simImgs = ArrayImgs.doubles(bleachedTimeStack, new long[] {timePointData.getBasicStackDimensions().xsize,timePointData.getBasicStackDimensions().ysize,ANALYZE_COUNT});
// SCIFIOImgPlus<DoubleType> annotatedZProjectedSimPostBleachData = new SCIFIOImgPlus<>(simImgs,newImgPlusName /*"Sim Data "+diffusionRate*/,new AxisType[] {Axes.X,Axes.Y,Axes.TIME});
// //    	RandomAccessibleInterval<DoubleType> simExtracted = ij.op().transform().crop(annotatedSimData, simExtractInterval);
// //showAndZoom(ij, "Sim Data "+diffusionRate, annotatedZProjectedSimPostBleachData, 4);
// return annotatedZProjectedSimPostBleachData;
// }
// public static double[] getNormalizedZProjected(VCellHelper.TimePointData timePointData,double[] normalizer) throws Exception{
// BasicStackDimensions basicStackDimensions = timePointData.getBasicStackDimensions();//VCellHelper.getDimensions(nodes.item(0));
// //Sum pixel values in Z direction to match experimental data (open pinhole confocal, essentially brightfield)
// int xysize = basicStackDimensions.xsize*basicStackDimensions.ysize;
// double[] normalizedData = new double[xysize];
// for (int i = 0; i < timePointData.getTimePointData().length; i++) {
// normalizedData[(i%xysize)]+= timePointData.getTimePointData()[i];
// }
// if(normalizer != null) {
// for (int i = 0; i < normalizedData.length; i++) {
// if(normalizedData[i] != 0) {
// normalizedData[i] = (normalizedData[i]+Double.MIN_VALUE)/(normalizer[i]+Double.MIN_VALUE);
// }
// }
// }
// return normalizedData;
// }
// public static void checkSizes(BasicStackDimensions basicStackDimensions,int xsize,int ysize,int zsize) throws Exception{
// if(basicStackDimensions.xsize != xsize || basicStackDimensions.ysize != ysize || basicStackDimensions.zsize != zsize) {
// throw new Exception("One or more sim data xyz dimensions="+basicStackDimensions.xsize+","+basicStackDimensions.ysize+","+basicStackDimensions.zsize+" does not match expected xyz sizes="+xsize+","+ysize+","+zsize);
// }
// }
public static double calcMSE(ImageJ ij, SCIFIOImgPlus<DoubleType> annotatedZProjectedSimPostBleachData, ExampleDatasets exampleDatasets, FinalInterval analyzeOrigInterval) throws Exception {
    // Calculate mean-squared-error as example, normalize experimental data by dividing by a prebleach image
    RandomAccessibleInterval<? extends RealType<?>> zProjectedExperimentalPostBleach = ij.op().transform().crop(exampleDatasets.experimentalData, analyzeOrigInterval);
    Cursor<DoubleType> zProjectedSimPostBleachDataCursor = IterableRandomAccessibleInterval.create(annotatedZProjectedSimPostBleachData).localizingCursor();
    Cursor<? extends RealType<?>> zProjectedExpPostBleachDataCursor = IterableRandomAccessibleInterval.create(zProjectedExperimentalPostBleach).localizingCursor();
    IterableRandomAccessibleInterval<? extends RealType<?>> zProjectedPreBleachInterval = IterableRandomAccessibleInterval.create(exampleDatasets.preBleachImage);
    BigDecimal sumSquaredDiff = new BigDecimal(0);
    int[] analysisPosition = new int[exampleDatasets.analysisROI.numDimensions()];
    int[] preBleachPosition = new int[zProjectedPreBleachInterval.numDimensions()];
    int[] experimentalPosition = new int[zProjectedExperimentalPostBleach.numDimensions()];
    int[] simulationPosition = new int[annotatedZProjectedSimPostBleachData.numDimensions()];
    int numValsInMask = 0;
    while (zProjectedSimPostBleachDataCursor.hasNext()) {
        Cursor<UnsignedByteType> analysisCursor = exampleDatasets.analysisROI.localizingCursor();
        Cursor<? extends RealType<?>> preBleachNormalizingCursor = zProjectedPreBleachInterval.localizingCursor();
        while (analysisCursor.hasNext()) {
            boolean maskBit = !(analysisCursor.next().get() == 0);
            DoubleType simPostBleachVal = zProjectedSimPostBleachDataCursor.next();
            RealType<?> expPostBleachVal = zProjectedExpPostBleachDataCursor.next();
            RealType<?> preBleachNormalizingVal = preBleachNormalizingCursor.next();
            if (!maskBit) {
                // skip areas where analysis mask is 0
                continue;
            }
            // Get the position of all the cursors and check they are in sync
            analysisCursor.localize(analysisPosition);
            preBleachNormalizingCursor.localize(preBleachPosition);
            zProjectedExpPostBleachDataCursor.localize(experimentalPosition);
            zProjectedSimPostBleachDataCursor.localize(simulationPosition);
            // System.out.println("analysis="+Arrays.toString(analysisPosition)+" prebleach="+Arrays.toString(preBleachPosition)+" exp="+Arrays.toString(experimentalPosition)+" sim="+Arrays.toString(simulationPosition));
            if (!Arrays.equals(analysisPosition, preBleachPosition) || !Arrays.equals(experimentalPosition, simulationPosition)) {
                throw new Exception("Cursor positions not equal");
            }
            if (analysisPosition[0] != experimentalPosition[0] || analysisPosition[1] != experimentalPosition[1]) {
                // check xy are same
                throw new Exception("XY Cursor position not equal for analysisROI mask and experimental data");
            }
            double normalizedExpDataVal = 0;
            if (expPostBleachVal.getRealDouble() != 0) {
                normalizedExpDataVal = (expPostBleachVal.getRealDouble()) / (preBleachNormalizingVal.getRealDouble() + Double.MIN_VALUE);
            }
            double diff = simPostBleachVal.get() - (normalizedExpDataVal);
            sumSquaredDiff = sumSquaredDiff.add(new BigDecimal(Math.pow(diff, 2.0)));
            numValsInMask++;
        }
    }
    return sumSquaredDiff.divide(new BigDecimal(numValsInMask), 8, RoundingMode.HALF_UP).doubleValue();
}
Also used : UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType) BigDecimal(java.math.BigDecimal) DoubleType(net.imglib2.type.numeric.real.DoubleType)

Example 5 with UnsignedByteType

use of net.imglib2.type.numeric.integer.UnsignedByteType in project vcell by virtualcell.

the class ProjectService method saveDataset.

private void saveDataset(Dataset dataset, Path path) throws IOException {
    Dataset datasetToSave = dataset.duplicate();
    // SCIFIO cannot save 1-bit images so we must convert to 8-bit
    if (datasetToSave.firstElement() instanceof BitType) {
        @SuppressWarnings("unchecked") Img<BitType> img = (Img<BitType>) dataset.getImgPlus().getImg();
        Img<UnsignedByteType> converted = opService.convert().uint8(img);
        ImgPlus<UnsignedByteType> convertedImgPlus = new ImgPlus<>(converted, dataset.getName());
        datasetToSave.setImgPlus(convertedImgPlus);
    }
    String name = dataset.getName();
    if (FilenameUtils.getExtension(name).isEmpty()) {
        // Default save extension
        name += ".tif";
    }
    Path filePath = Paths.get(path.toString(), name);
    datasetIOService.save(datasetToSave, filePath.toString());
}
Also used : Path(java.nio.file.Path) Img(net.imglib2.img.Img) BitType(net.imglib2.type.logic.BitType) ImgPlus(net.imagej.ImgPlus) Dataset(net.imagej.Dataset) UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType)

Aggregations

UnsignedByteType (net.imglib2.type.numeric.integer.UnsignedByteType)14 DoubleType (net.imglib2.type.numeric.real.DoubleType)5 Random (java.util.Random)4 AbstractOpTest (net.imagej.ops.AbstractOpTest)4 Test (org.junit.Test)4 FinalDimensions (net.imglib2.FinalDimensions)3 Img (net.imglib2.img.Img)3 BitType (net.imglib2.type.logic.BitType)3 File (java.io.File)2 IOException (java.io.IOException)2 Dataset (net.imagej.Dataset)2 ImgPlus (net.imagej.ImgPlus)2 FinalInterval (net.imglib2.FinalInterval)2 ArrayImgFactory (net.imglib2.img.array.ArrayImgFactory)2 FloatType (net.imglib2.type.numeric.real.FloatType)2 ImageJ (ij.ImageJ)1 ImagePlus (ij.ImagePlus)1 BufferedImage (java.awt.image.BufferedImage)1 BigDecimal (java.math.BigDecimal)1 URL (java.net.URL)1