Ejemplo n.º 1
0
 public void splitRGB(ImagePlus imp) {
   boolean keepSource = IJ.altKeyDown();
   String title = imp.getTitle();
   Calibration cal = imp.getCalibration();
   int pos = imp.getCurrentSlice();
   ImageStack[] channels = splitRGB(imp.getStack(), keepSource);
   if (!keepSource) {
     imp.unlock();
     imp.changes = false;
     imp.close();
   }
   ImagePlus rImp = new ImagePlus(title + " (red)", channels[0]);
   rImp.setCalibration(cal);
   rImp.show();
   rImp.setSlice(pos);
   if (IJ.isMacOSX()) IJ.wait(500);
   ImagePlus gImp = new ImagePlus(title + " (green)", channels[1]);
   gImp.setCalibration(cal);
   gImp.show();
   gImp.setSlice(pos);
   if (IJ.isMacOSX()) IJ.wait(500);
   ImagePlus bImp = new ImagePlus(title + " (blue)", channels[2]);
   bImp.setCalibration(cal);
   bImp.show();
   bImp.setSlice(pos);
 }
Ejemplo n.º 2
0
 private ImagePlus openFFT(ImagePlus imp) {
   ImageProcessor ip = imp.getProcessor();
   FHT fht = new FHT(ip, true);
   ImageProcessor ps = fht.getPowerSpectrum();
   ImagePlus imp2 = new ImagePlus(imp.getTitle(), ps);
   imp2.setProperty("FHT", fht);
   imp2.setProperty("Info", imp.getInfoProperty());
   fht.originalWidth = (int) imp2.getNumericProperty("width");
   fht.originalHeight = (int) imp2.getNumericProperty("height");
   fht.originalBitDepth = (int) imp2.getNumericProperty("bitdepth");
   fht.originalColorModel = ip.getColorModel();
   imp2.setCalibration(imp.getCalibration());
   return imp2;
 }
Ejemplo n.º 3
0
  private ImagePlus findSurfaceVoxels(final ImagePlus imp) {
    final int w = imp.getWidth();
    final int h = imp.getHeight();
    final int d = imp.getImageStackSize();
    final ImageStack stack = imp.getImageStack();
    final ImageStack surfaceStack = new ImageStack(w, h, d);

    for (int z = 0; z < d; z++) {
      IJ.showStatus("Finding surface voxels");
      final byte[] pixels = (byte[]) stack.getPixels(z + 1);
      surfaceStack.setPixels(pixels.clone(), z + 1);
      final ImageProcessor surfaceIP = surfaceStack.getProcessor(z + 1);
      for (int y = 0; y < h; y++) {
        checkNeighbours:
        for (int x = 0; x < w; x++) {
          if (getPixel(stack, x, y, z, w, h, d) == (byte) 0) continue;
          for (int nz = -1; nz < 2; nz++) {
            final int znz = z + nz;
            for (int ny = -1; ny < 2; ny++) {
              final int yny = y + ny;
              for (int nx = -1; nx < 2; nx++) {
                final int xnx = x + nx;
                final byte pixel = getPixel(stack, xnx, yny, znz, w, h, d);
                if (pixel == (byte) 0) continue checkNeighbours;
              }
            }
          }
          // we checked all the neighbours for a 0
          // but didn't find one, so this is not a surface voxel
          surfaceIP.set(x, y, (byte) 1);
        }
      }
    }
    // turn all the 1's into 0's
    final int wh = w * h;
    for (int z = 0; z < d; z++) {
      IJ.showStatus("Finding surface voxels");
      final ImageProcessor ip = surfaceStack.getProcessor(z + 1);
      for (int i = 0; i < wh; i++) {
        if (ip.get(i) == (byte) 1) ip.set(i, (byte) 0);
      }
    }

    final ImagePlus surfaceImp = new ImagePlus("Surface");
    surfaceImp.setStack(surfaceStack);
    surfaceImp.setCalibration(imp.getCalibration());
    return surfaceImp;
  }
Ejemplo n.º 4
0
 void checkForCalibrationConflict(ImagePlus imp, Calibration cal) {
   Calibration gcal = imp.getGlobalCalibration();
   if (gcal == null || !showConflictMessage || IJ.isMacro()) return;
   if (cal.pixelWidth == gcal.pixelWidth && cal.getUnit().equals(gcal.getUnit())) return;
   GenericDialog gd = new GenericDialog(imp.getTitle());
   gd.addMessage("The calibration of this image conflicts\nwith the current global calibration.");
   gd.addCheckbox("Disable_Global Calibration", true);
   gd.addCheckbox("Disable_these Messages", false);
   gd.showDialog();
   if (gd.wasCanceled()) return;
   boolean disable = gd.getNextBoolean();
   if (disable) {
     imp.setGlobalCalibration(null);
     imp.setCalibration(cal);
     WindowManager.repaintImageWindows();
   }
   boolean dontShow = gd.getNextBoolean();
   if (dontShow) showConflictMessage = false;
 }
Ejemplo n.º 5
0
 // extract range of slices
 ImagePlus stackRange(ImagePlus imp, int first, int last, int inc, String title) throws Exception {
   ImageStack stack = imp.getStack();
   ImageStack stack2 = null;
   Roi roi = imp.getRoi();
   for (int i = first, j = 0; i <= last; i += inc) {
     // IJ.log(first+" "+last+" "+inc+" "+i);
     IJ.showProgress(i - first, last - first);
     int currSlice = i - j;
     ImageProcessor ip2 = stack.getProcessor(currSlice);
     // ip2.setRoi(roi);
     // ip2 = ip2.crop();
     if (stack2 == null) stack2 = new ImageStack(ip2.getWidth(), ip2.getHeight());
     stack2.addSlice(stack.getSliceLabel(currSlice), ip2);
   }
   ImagePlus substack = imp.createImagePlus();
   substack.setStack(title, stack2);
   substack.setCalibration(imp.getCalibration());
   return substack;
 }
Ejemplo n.º 6
0
 /** Splits the specified image into separate channels. */
 public static ImagePlus[] split(ImagePlus imp) {
   if (imp.getType() == ImagePlus.COLOR_RGB) {
     ImageStack[] stacks = splitRGB(imp.getStack(), true);
     ImagePlus[] images = new ImagePlus[3];
     images[0] = new ImagePlus("red", stacks[0]);
     images[1] = new ImagePlus("green", stacks[1]);
     images[2] = new ImagePlus("blue", stacks[2]);
     return images;
   }
   int width = imp.getWidth();
   int height = imp.getHeight();
   int channels = imp.getNChannels();
   int slices = imp.getNSlices();
   int frames = imp.getNFrames();
   int bitDepth = imp.getBitDepth();
   int size = slices * frames;
   Vector images = new Vector();
   HyperStackReducer reducer = new HyperStackReducer(imp);
   for (int c = 1; c <= channels; c++) {
     ImageStack stack2 = new ImageStack(width, height, size); // create empty stack
     stack2.setPixels(
         imp.getProcessor().getPixels(), 1); // can't create ImagePlus will null 1st image
     ImagePlus imp2 = new ImagePlus("C" + c + "-" + imp.getTitle(), stack2);
     stack2.setPixels(null, 1);
     imp.setPosition(c, 1, 1);
     imp2.setDimensions(1, slices, frames);
     imp2.setCalibration(imp.getCalibration());
     reducer.reduce(imp2);
     if (imp.isComposite() && ((CompositeImage) imp).getMode() == IJ.GRAYSCALE)
       IJ.run(imp2, "Grays", "");
     if (imp2.getNDimensions() > 3) imp2.setOpenAsHyperStack(true);
     images.add(imp2);
   }
   ImagePlus[] array = new ImagePlus[images.size()];
   return (ImagePlus[]) images.toArray(array);
 }
Ejemplo n.º 7
0
  public void run(String arg) {
    ImageCheck ic = new ImageCheck();
    if (!ImageCheck.checkEnvironment()) return;
    ImagePlus imp = IJ.getImage();
    if (!ic.isBinary(imp)) {
      IJ.error("8-bit binary (black and white only) image required.");
      return;
    }

    if (!ic.isVoxelIsotropic(imp, 1E-3)) {
      if (IJ.showMessageWithCancel(
          "Anisotropic voxels",
          "This image contains anisotropic voxels, which will\n"
              + "result in incorrect thickness calculation.\n\n"
              + "Consider rescaling your data so that voxels are isotropic\n"
              + "(Image > Scale...).\n\n"
              + "Continue anyway?")) {
      } else return;
    }
    GenericDialog gd = new GenericDialog("Options");
    gd.addCheckbox("Thickness", true);
    gd.addCheckbox("Spacing", false);
    gd.addCheckbox("Graphic Result", true);
    gd.addCheckbox("Use_ROI_Manager", false);
    gd.addCheckbox("Mask thickness map", true);
    gd.addHelp("http://bonej.org/thickness");
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    boolean doThickness = gd.getNextBoolean();
    boolean doSpacing = gd.getNextBoolean();
    boolean doGraphic = gd.getNextBoolean();
    boolean doRoi = gd.getNextBoolean();
    boolean doMask = gd.getNextBoolean();

    long startTime = System.currentTimeMillis();
    String title = stripExtension(imp.getTitle());

    RoiManager roiMan = RoiManager.getInstance();
    // calculate trabecular thickness (Tb.Th)
    if (doThickness) {
      boolean inverse = false;
      ImagePlus impLTC = new ImagePlus();
      if (doRoi && roiMan != null) {
        ImageStack stack = RoiMan.cropStack(roiMan, imp.getStack(), true, 0, 1);
        ImagePlus crop = new ImagePlus(imp.getTitle(), stack);
        crop.setCalibration(imp.getCalibration());
        impLTC = getLocalThickness(crop, inverse, doMask);
      } else impLTC = getLocalThickness(imp, inverse, doMask);
      impLTC.setTitle(title + "_Tb.Th");
      impLTC.setCalibration(imp.getCalibration());
      double[] stats = StackStats.meanStdDev(impLTC);
      insertResults(imp, stats, inverse);
      if (doGraphic && !Interpreter.isBatchMode()) {
        impLTC.show();
        impLTC.setSlice(1);
        impLTC.getProcessor().setMinAndMax(0, stats[2]);
        IJ.run("Fire");
      }
    }
    if (doSpacing) {
      boolean inverse = true;
      ImagePlus impLTCi = new ImagePlus();
      if (doRoi && roiMan != null) {
        ImageStack stack = RoiMan.cropStack(roiMan, imp.getStack(), true, 255, 1);
        ImagePlus crop = new ImagePlus(imp.getTitle(), stack);
        crop.setCalibration(imp.getCalibration());
        impLTCi = getLocalThickness(crop, inverse, doMask);
      } else impLTCi = getLocalThickness(imp, inverse, doMask);
      // check marrow cavity size (i.e. trabcular separation, Tb.Sp)
      impLTCi.setTitle(title + "_Tb.Sp");
      impLTCi.setCalibration(imp.getCalibration());
      double[] stats = StackStats.meanStdDev(impLTCi);
      insertResults(imp, stats, inverse);
      if (doGraphic && !Interpreter.isBatchMode()) {
        impLTCi.show();
        impLTCi.setSlice(1);
        impLTCi.getProcessor().setMinAndMax(0, stats[2]);
        IJ.run("Fire");
      }
    }
    IJ.showProgress(1.0);
    IJ.showStatus("Done");
    double duration = ((double) System.currentTimeMillis() - (double) startTime) / (double) 1000;
    IJ.log("Duration = " + IJ.d2s(duration, 3) + " s");
    UsageReporter.reportEvent(this).send();
    return;
  }
Ejemplo n.º 8
0
  static ImagePlus openNewFormat(String path, DataInputStream dis) throws IOException {
    // ImagePlus imp;
    // New version of VM using 12 parameter fields
    int version = reverse(dis.readInt());
    int type = reverse(dis.readInt());
    int size1 = reverse(dis.readInt());
    int size2 = reverse(dis.readInt());
    int size3 = reverse(dis.readInt());
    ImageStack stack = new ImageStack(size1, size2);

    int voxelUnit = reverse(dis.readInt());
    float voxelWidth = Float.intBitsToFloat(reverse(dis.readInt()));
    float voxelHeight = Float.intBitsToFloat(reverse(dis.readInt()));
    float voxelDepth = Float.intBitsToFloat(reverse(dis.readInt()));

    final int numPixels = size1 * size2;
    final int bufferSize = 4 * numPixels;

    final byte[] buffer = new byte[bufferSize];

    // write pixels
    for (int z = 0; z < size3; ++z) {

      final float[][] pixels = new float[size1][size2];

      int n = dis.read(buffer, 0, bufferSize);

      for (int j = 0; j < bufferSize; j += 4) {
        int tmp =
            (int)
                (((buffer[j + 3] & 0xff) << 24)
                    | ((buffer[j + 2] & 0xff) << 16)
                    | ((buffer[j + 1] & 0xff) << 8)
                    | (buffer[j] & 0xff));

        int currentPos = j / 4;
        int y = currentPos / size2;
        int x = currentPos % size2;

        if (type == 5) pixels[y][x] = Float.intBitsToFloat(tmp); // float type
        else if (type == 2) pixels[y][x] = (float) tmp; // int type
      }
      final FloatProcessor fp = new FloatProcessor(pixels);
      stack.addSlice(fp);
    }

    ImagePlus imp = new ImagePlus(path, stack);

    if (size3 > 1) {
      imp.setSlice(size3 / 2);
      ImageProcessor ip = imp.getProcessor();
      ip.resetMinAndMax();
      imp.setDisplayRange(ip.getMin(), ip.getMax());
    }

    Calibration calibration = new Calibration();
    String unit = intToUnitString(voxelUnit);
    calibration.setXUnit(unit);
    calibration.setYUnit(unit);
    calibration.setZUnit(unit);
    calibration.pixelWidth = voxelWidth;
    calibration.pixelHeight = voxelHeight;
    calibration.pixelDepth = voxelDepth;
    imp.setCalibration(calibration);

    return imp;
  }
  protected static <T extends RealType<T>> CompositeImage createOverlay(
      final T targetType,
      final ImagePlus imp1,
      final ImagePlus imp2,
      final InvertibleBoundable finalModel1,
      final InvertibleBoundable finalModel2,
      final int dimensionality) {
    final ArrayList<ImagePlus> images = new ArrayList<ImagePlus>();
    images.add(imp1);
    images.add(imp2);

    final int ntimepoints = Math.min(imp1.getNFrames(), imp2.getNFrames());

    final ImagePlus[] cis = new ImagePlus[ntimepoints];

    final ArrayList<InvertibleBoundable> models = new ArrayList<InvertibleBoundable>();
    for (int i = 0; i < ntimepoints; ++i) {
      models.add(finalModel1);
      models.add(finalModel2);
    }

    for (int tp = 1; tp <= ntimepoints; ++tp) {
      if (useNearestNeighborInterpolation)
        cis[tp - 1] =
            createOverlay(
                targetType,
                images,
                models,
                dimensionality,
                tp,
                new NearestNeighborInterpolatorFactory<FloatType>(
                    new OutOfBoundsStrategyValueFactory<FloatType>()));
      else
        cis[tp - 1] =
            createOverlay(
                targetType,
                images,
                models,
                dimensionality,
                tp,
                new LinearInterpolatorFactory<FloatType>(
                    new OutOfBoundsStrategyValueFactory<FloatType>()));
    }

    final ImagePlus imp =
        new Concatenator()
            .concatenateHyperstacks(
                cis, "Fused " + imp1.getShortTitle() + " & " + imp2.getShortTitle(), false);

    // get the right number of channels, slices and frames
    final int numChannels = imp1.getNChannels() + imp2.getNChannels();
    final int nSlices = cis[0].getNSlices();

    // Set the right dimensions
    imp.setDimensions(numChannels, nSlices, ntimepoints);

    // Copy calibration
    imp.setCalibration(imp1.getCalibration());

    return new CompositeImage(imp, CompositeImage.COMPOSITE);
  }
Ejemplo n.º 10
0
  /**
   * @param img
   * @param processorFactory
   * @param converter
   * @return wrapped {@link ImagePlus}
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static final <T extends RealType<T>> ImagePlus wrap(
      final ImgPlus<T> img,
      final ImageProcessorFactory processorFactory,
      final Converter<T, FloatType> converter) {
    // we always want to have 5 dimensions
    final RandomAccessibleInterval permuted = extendAndPermute(img);

    final int width = (int) permuted.dimension(0);
    final int height = (int) permuted.dimension(1);

    final ImagePlus r = new ImagePlus();
    final ImageStack is = new ImageStack(width, height);

    final RandomAccessibleInterval<T> access =
        img.iterationOrder().equals(((IterableRealInterval<?>) permuted).iterationOrder())
            ? img
            : permuted;

    final IntervalIterator ii = createIntervalIterator(access);

    final long[] min = new long[access.numDimensions()];
    final long[] max = new long[access.numDimensions()];

    max[0] = permuted.max(0);
    max[1] = permuted.max(1);

    // number of planes = num tasks
    int numSlices = 1;
    for (int d = 2; d < access.numDimensions(); d++) {
      numSlices *= access.dimension(d);
    }

    // parallelization
    final ImageProcessor[] slices = new ImageProcessor[numSlices];
    final ExecutorService service =
        new ThreadPoolExecutorService(
            KNIMEConstants.GLOBAL_THREAD_POOL.createSubPool(KNIPConstants.THREADS_PER_NODE));

    final ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>();
    final T inType = img.firstElement();

    int i = 0;
    while (ii.hasNext()) {
      ii.fwd();

      for (int d = 2; d < ii.numDimensions(); d++) {
        min[d] = ii.getIntPosition(d);
        max[d] = min[d];
      }

      final int proxy = i++;

      futures.add(
          service.submit(
              new Callable<Void>() {

                final FinalInterval tmp = new FinalInterval(min, max);

                @Override
                public Void call() throws Exception {

                  final Cursor<T> cursor = Views.iterable(Views.interval(access, tmp)).cursor();

                  final ImageProcessor ip = processorFactory.createProcessor(width, height, inType);

                  final FloatType outProxy = new FloatType();
                  for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++) {
                      converter.convert(cursor.next(), outProxy);
                      ip.setf(x, y, outProxy.get());
                    }
                  }
                  slices[proxy] = ip;

                  return null;
                }
              }));
    }

    for (final Future<Void> f : futures) {
      try {
        f.get();
      } catch (final InterruptedException e) {
        e.printStackTrace();
      } catch (final ExecutionException e) {
        e.printStackTrace();
      }
    }

    // add slices to stack
    for (ImageProcessor slice : slices) {
      is.addSlice("", slice);
    }

    // set calibration
    final double[] newCalibration = getNewCalibration(img);
    Calibration cal = new Calibration();
    cal.pixelWidth = newCalibration[0];
    cal.pixelHeight = newCalibration[1];
    cal.pixelDepth = newCalibration[3];
    r.setCalibration(cal);

    r.setStack(
        is, (int) permuted.dimension(2), (int) permuted.dimension(3), (int) permuted.dimension(4));
    r.setTitle(img.getName());

    return r;
  }
Ejemplo n.º 11
0
  /*
   * (non-Javadoc)
   *
   * @see ij.plugin.filter.PlugInFilter#run(ij.process.ImageProcessor)
   */
  @Override
  public void run(final ImageProcessor ip) {
    /*
     * Each correction contains of implementations of the abstract classes
     * CoordinateCorrector and a IntensityCorrector that can be can be
     * combined as you want.
     *
     * By using getFunctionWidth() and getFunctionBorders() the
     * characterisation results are loaded and an implementation of the
     * Levenberg–Marquardt algorithm (LMA) is used to fit functions to the
     * discrete values.
     */
    IJ.showStatus("Preparing correction...");
    importer = new DataImporter(pathResults, false);
    final SR_EELS_Polynomial_2D widthFunction = getFunctionWidth();
    inputProcessor.setWidthFunction(widthFunction);
    final SR_EELS_Polynomial_2D borderFunction = getFunctionBorders();
    inputProcessor.setBorderFunction(borderFunction);
    /*
     * TODO: Add the used correction methods to the image title.
     */
    outputProcessor = widthFunction.createOutputImage();
    outputImage = new ImagePlus(title + "_corrected", outputProcessor);
    final Calibration cal = new Calibration(inputImp);
    cal.pixelHeight = widthFunction.getPixelHeight();
    outputImage.setCalibration(cal);
    final CoordinateCorrector coordinateCorrection =
        new FullCoordinateCorrection(inputProcessor, outputProcessor);
    final IntensityCorrector intensityCorrection =
        new SimpleIntensityCorrection(inputProcessor, coordinateCorrection);
    /*
     * Each line of the image is a step that is visualise by the progress
     * bar of ImageJ.
     */
    setupProgress(outputProcessor.getHeight());
    if (EFTEMj_Debug.getDebugLevel() == EFTEMj_Debug.DEBUG_FULL) {
      for (int x2 = 0; x2 < outputProcessor.getHeight(); x2++) {
        for (int x1 = 0; x1 < outputProcessor.getWidth(); x1++) {
          final float intensity = intensityCorrection.getIntensity(x1, x2);
          outputProcessor.setf(x1, x2, intensity);
        }
        updateProgress();
      }
    } else {
      /*
       * The ExecutorService is used to handle the multithreading. see
       * http://www.vogella.com/tutorials/JavaConcurrency/article.html#
       * threadpools
       */
      final ExecutorService executorService =
          Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
      for (int x2 = 0; x2 < outputProcessor.getHeight(); x2++) {
        final int x2Temp = x2;
        executorService.execute(
            new Runnable() {

              @Override
              public void run() {
                for (int x1 = 0; x1 < outputProcessor.getWidth(); x1++) {
                  final float intensity = intensityCorrection.getIntensity(x1, x2Temp);
                  outputProcessor.setf(x1, x2Temp, intensity);
                }
                updateProgress();
              }
            });
      }
      executorService.shutdown();
      try {
        executorService.awaitTermination(30, TimeUnit.MINUTES);
      } catch (final InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 12
0
 /**
  * Attempts to open the specified file as a tiff, bmp, dicom, fits, pgm, gif or jpeg image.
  * Returns an ImagePlus object if successful. Modified by Gregory Jefferis to call
  * HandleExtraFileTypes plugin if the file type is unrecognised.
  *
  * @see ij.IJ#openImage(String)
  */
 public ImagePlus openImage(String directory, String name) {
   ImagePlus imp;
   FileOpener.setSilentMode(silentMode);
   if (directory.length() > 0 && !(directory.endsWith("/") || directory.endsWith("\\")))
     directory += Prefs.separator;
   String path = directory + name;
   fileType = getFileType(path);
   if (IJ.debugMode) IJ.log("openImage: \"" + types[fileType] + "\", " + path);
   switch (fileType) {
     case TIFF:
       imp = openTiff(directory, name);
       return imp;
     case DICOM:
       imp = (ImagePlus) IJ.runPlugIn("ij.plugin.DICOM", path);
       if (imp.getWidth() != 0) return imp;
       else return null;
     case TIFF_AND_DICOM:
       // "hybrid" files created by GE-Senographe 2000 D */
       imp = openTiff(directory, name);
       ImagePlus imp2 = (ImagePlus) IJ.runPlugIn("ij.plugin.DICOM", path);
       if (imp != null && imp2 != null) {
         imp.setProperty("Info", imp2.getProperty("Info"));
         imp.setCalibration(imp2.getCalibration());
       }
       if (imp == null) imp = imp2;
       return imp;
     case FITS:
       imp = (ImagePlus) IJ.runPlugIn("ij.plugin.FITS_Reader", path);
       if (imp.getWidth() != 0) return imp;
       else return null;
     case PGM:
       imp = (ImagePlus) IJ.runPlugIn("ij.plugin.PGM_Reader", path);
       if (imp.getWidth() != 0) {
         if (imp.getStackSize() == 3 && imp.getBitDepth() == 16)
           imp = new CompositeImage(imp, IJ.COMPOSITE);
         return imp;
       } else return null;
     case JPEG:
       imp = openJpegOrGif(directory, name);
       if (imp != null && imp.getWidth() != 0) return imp;
       else return null;
     case GIF:
       imp = (ImagePlus) IJ.runPlugIn("ij.plugin.GIF_Reader", path);
       if (imp != null && imp.getWidth() != 0) return imp;
       else return null;
     case PNG:
       imp = openUsingImageIO(directory + name);
       if (imp != null && imp.getWidth() != 0) return imp;
       else return null;
     case BMP:
       imp = (ImagePlus) IJ.runPlugIn("ij.plugin.BMP_Reader", path);
       if (imp.getWidth() != 0) return imp;
       else return null;
     case ZIP:
       return openZip(path);
     case AVI:
       AVI_Reader reader = new AVI_Reader();
       reader.displayDialog(!IJ.macroRunning());
       reader.run(path);
       return reader.getImagePlus();
     case UNKNOWN:
     case TEXT:
       // Call HandleExtraFileTypes plugin to see if it can handle unknown format
       int[] wrap = new int[] {fileType};
       imp = openWithHandleExtraFileTypes(path, wrap);
       if (imp != null && imp.getNChannels() > 1) imp = new CompositeImage(imp, IJ.COLOR);
       fileType = wrap[0];
       if (imp == null && fileType == UNKNOWN && IJ.getInstance() == null)
         IJ.error("Opener", "Unsupported format or not found");
       return imp;
     default:
       return null;
   }
 }
Ejemplo n.º 13
0
  public void run(String arg) {
    imp = IJ.getImage();
    int stackSize = imp.getStackSize();
    if (imp == null) {
      IJ.noImage();
      return;
    }

    //  Make sure input image is a stack.
    if (stackSize == 1) {
      IJ.error("Z Project", "Stack required");
      return;
    }

    //  Check for inverting LUT.
    if (imp.getProcessor().isInvertedLut()) {
      if (!IJ.showMessageWithCancel("ZProjection", lutMessage)) return;
    }

    // Set default bounds.
    int channels = imp.getNChannels();
    int frames = imp.getNFrames();
    int slices = imp.getNSlices();
    isHyperstack =
        imp.isHyperStack()
            || (ij.macro.Interpreter.isBatchMode()
                && ((frames > 1 && frames < stackSize) || (slices > 1 && slices < stackSize)));
    boolean simpleComposite = channels == stackSize;
    if (simpleComposite) isHyperstack = false;
    startSlice = 1;
    if (isHyperstack) {
      int nSlices = imp.getNSlices();
      if (nSlices > 1) stopSlice = nSlices;
      else stopSlice = imp.getNFrames();
    } else stopSlice = stackSize;

    // Build control dialog
    GenericDialog gd = buildControlDialog(startSlice, stopSlice);
    gd.showDialog();
    if (gd.wasCanceled()) return;

    if (!imp.lock()) return; // exit if in use
    long tstart = System.currentTimeMillis();
    setStartSlice((int) gd.getNextNumber());
    setStopSlice((int) gd.getNextNumber());
    method = gd.getNextChoiceIndex();
    Prefs.set(METHOD_KEY, method);
    if (isHyperstack) {
      allTimeFrames = imp.getNFrames() > 1 && imp.getNSlices() > 1 ? gd.getNextBoolean() : false;
      doHyperStackProjection(allTimeFrames);
    } else if (imp.getType() == ImagePlus.COLOR_RGB) doRGBProjection(true);
    else doProjection(true);

    if (arg.equals("") && projImage != null) {
      long tstop = System.currentTimeMillis();
      projImage.setCalibration(imp.getCalibration());
      if (simpleComposite) IJ.run(projImage, "Grays", "");
      projImage.show("ZProjector: " + IJ.d2s((tstop - tstart) / 1000.0, 2) + " seconds");
    }

    imp.unlock();
    IJ.register(ZProjector.class);
    return;
  }