public static void SaveTif(TifFileInfo fi, string dir, ImageAnalyser IA)
        {
            try {
                //return;
                //Save pixel data
                switch (fi.bitsPerPixel)
                {
                case 8:
                    SaveTif_8bitRawData(fi, dir, IA);
                    break;

                case 16:
                    SaveTif_16bitRawData(fi, dir, IA);
                    break;

                default:
                    return;
                }
                //save metadata
                //string value = calculateCTTagValue(fi,IA);
                //image.SetField(TIFFTAG_CellTool_METADATA, value);
                //AddTag(dir, value);
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Save file error!");
            }
        }
Example #2
0
        public PlugInEngine(ToolStripMenuItem DeveloperToolStripMenuItem, ImageAnalyser IA)
        {
            this.DeveloperToolStripMenuItem = DeveloperToolStripMenuItem;
            this.IA = IA;

            PlugIns_TakeNames();
        }
        private static void SaveTif_16bitRawData1(TifFileInfo fi, string fileName, ImageAnalyser IA)
        {
            // Register the extender callback
            m_parentExtender = Tiff.SetTagExtender(TagExtender);
            string value = calculateCTTagValue(fi, IA);

            int numberOfPages = fi.imageCount;

            int width           = fi.sizeX;
            int height          = fi.sizeY;
            int samplesPerPixel = 1;
            int bitsPerSample   = fi.bitsPerPixel;

            using (Tiff output = Tiff.Open(fileName, "w"))
            {
                for (int page = 0; page < numberOfPages; page++)
                {
                    ushort[][] image = fi.image16bit[page];
                    output.SetField(TiffTag.IMAGELENGTH, height);
                    output.SetField(TiffTag.IMAGEWIDTH, width);
                    output.SetField(TiffTag.SAMPLESPERPIXEL, samplesPerPixel);
                    output.SetField(TiffTag.BITSPERSAMPLE, bitsPerSample);
                    output.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                    output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                    output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                    output.SetField(TiffTag.ROWSPERSTRIP, output.DefaultStripSize(0));
                    output.SetField(TiffTag.COMPRESSION, Compression.NONE);
                    output.SetField(TiffTag.IMAGEDESCRIPTION, ImageDetails());
                    // specify that it's a page within the multipage file
                    output.SetField(TiffTag.SUBFILETYPE, FileType.PAGE);
                    // specify the page number
                    output.SetField(TiffTag.PAGENUMBER, page, numberOfPages);

                    if (page == numberOfPages - 1)
                    {
                        // set the custom tag
                        output.SetField(TIFFTAG_CellTool_METADATA, value);
                    }

                    for (int i = 0; i < height; i++)
                    {
                        ushort[] samples = image[i];

                        byte[] buffer = new byte[samples.Length * sizeof(ushort)];
                        Buffer.BlockCopy(samples, 0, buffer, 0, buffer.Length);

                        output.WriteScanline(buffer, i);
                    }

                    output.WriteDirectory();
                }
            }

            // restore previous tag extender
            Tiff.SetTagExtender(m_parentExtender);
        }
        public CTChart_Properties(Panel propertiesPanel, Panel PropertiesBody, ImageAnalyser IA)
        {
            this.IA = IA;
            Ncalc   = new Ncalc_Adapter(IA);

            PropPanel = new PropertiesPanel_Item();
            PropPanel_Initialize(propertiesPanel, PropertiesBody);
            //GLControl event
            //IA.GLControl1.MouseDown += GLControl_MouseClick_tracking;
        }
        public CTChart_Series(Panel propertiesPanel, Panel PropertiesBody, ImageAnalyser IA)
        {
            this.IA = IA;

            PropPanel = new PropertiesPanel_Item();
            PropPanel_Initialize(propertiesPanel, PropertiesBody);

            string[] colMatrix = new string[] { "blue", "red", "#00b300", "#b300b3", "#00bfff", "#ffcc00", "#ff471a", "#cc6699", "#39e600"
                                                , "#00b3b3", "#ffcc66", "#7575a3", "#ff1a1a", "#ff0055", "#8a00e6", "#bf8040",
                                                "#53c68c", "#ace600", "#b33c00", "#ff6666" };

            tv.ImageList           = new ImageList();
            tv.ImageList.ImageSize = new Size(20, 16);

            foreach (string val in colMatrix)
            {
                RefColors.Add(ColorTranslator.FromHtml(val));
                createImagesFortTV(ColorTranslator.FromHtml(val));
            }
        }
Example #6
0
        private TifFileInfo FindFI(ImageAnalyser IA)
        {
            TifFileInfo fi = null;

            try
            {
                fi = IA.TabPages.TabCollections[IA.TabPages.SelectedIndex].tifFI;
            }
            catch { return(null); }

            if (fi == null)
            {
                return(null);
            }
            if (fi.available == false)
            {
                return(null);
            }

            return(fi);
        }
Example #7
0
        public void Save(ImageAnalyser IA)
        {
            TifFileInfo tifFI = this.tifFI;

            if (tifFI != null)
            {
                if (!tifFI.available)
                {
                    MessageBox.Show("Image is not avaliable!\nTry again later.");
                    return;
                }

                string dir = tifFI.Dir;
                //background worker
                var bgw = new BackgroundWorker();
                bgw.WorkerReportsProgress = true;
                //Add handlers to the backgroundworker
                //Reports when is finished

                bgw.DoWork += new DoWorkEventHandler(delegate(Object o, DoWorkEventArgs a)
                {
                    //check is the directory exist
                    if (dir.IndexOf("\\") > -1)
                    {
                        string checkDir = dir.Substring(0, dir.LastIndexOf("\\"));
                        checkDir        = OSStringConverter.StringToDir(checkDir);
                        if (!System.IO.Directory.Exists(checkDir))
                        {
                            System.IO.Directory.CreateDirectory(checkDir);
                        }
                    }
                    //save file
                    FileEncoder.SaveTif(tifFI, dir, IA);
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(0);
                });

                bgw.ProgressChanged += new ProgressChangedEventHandler(delegate(Object o, ProgressChangedEventArgs a)
                {
                    if (a.ProgressPercentage == 0)
                    {
                        Saved = true;
                        if (tifFI != null)
                        {
                            tifFI.available = true;
                        }
                        IA.FileBrowser.StatusLabel.Text = "Ready";
                    }
                });

                //Start background worker
                tifFI.available = false;
                IA.FileBrowser.StatusLabel.Text = "Saving Tif Image...";

                IA.EnabletrackBars(false);
                bgw.RunWorkerAsync();
                //continue when the sae is done
                while (bgw.IsBusy)
                {
                    Application.DoEvents(); //This call is very important if you want to have a progress bar and want to update it
                                            //from the Progress event of the background worker.
                    Thread.Sleep(10);       //This call waits if the loop continues making sure that the CPU time gets freed before
                                            //re-checking.
                }

                IA.EnabletrackBars(true);
            }
            else if (ResultsExtractor != null)
            {
                //check is the directory exist
                if (dir.IndexOf("\\") > -1)
                {
                    string checkDir = dir.Substring(0, dir.LastIndexOf("\\"));
                    checkDir = OSStringConverter.StringToDir(checkDir);
                    if (!System.IO.Directory.Exists(checkDir))
                    {
                        System.IO.Directory.CreateDirectory(checkDir);
                    }
                }

                var bgw = ResultsExtractor.FileSaver.SaveCTDataFile(
                    (Cell_Tool_3.ResultsExtractor.MyForm)
                    this.ResultsExtractor.myPanel, dir);

                //continue when the sae is done
                while (bgw.IsBusy)
                {
                    Application.DoEvents(); //This call is very important if you want to have a progress bar and want to update it
                                            //from the Progress event of the background worker.
                    Thread.Sleep(10);       //This call waits if the loop continues making sure that the CPU time gets freed before
                                            //re-checking.
                }
            }
        }
        public AutoApplySettingsClass(Button startBtn, ComboBox LibTB, ImageAnalyser IA)
        {
            this.startBtn = startBtn;
            this.LibTB    = LibTB;
            this.IA       = IA;

            Form dialog = this;

            dialog.FormBorderStyle = FormBorderStyle.FixedDialog;
            dialog.Text            = "Auto Settings";
            dialog.StartPosition   = FormStartPosition.CenterScreen;
            dialog.WindowState     = FormWindowState.Normal;
            dialog.BackColor       = IA.FileBrowser.BackGround2Color1;
            dialog.ForeColor       = IA.FileBrowser.ShriftColor1;
            dialog.MinimizeBox     = false;
            dialog.MaximizeBox     = false;
            dialog.Width           = 250;
            dialog.Height          = 335;

            #region Add controls
            this.SuspendLayout();

            //ApplyToNewImage checkbox

            ApplyToNewCheckB.Text     = "Apply settings when new image is opened";
            ApplyToNewCheckB.Location = new System.Drawing.Point(5, 5);
            ApplyToNewCheckB.Width    = 250;
            this.Controls.Add(ApplyToNewCheckB);
            ApplyToNewCheckB.CheckedChanged += ApplyToNewCheckB_Checked;
            //Title
            Label titleLabel = new Label();
            titleLabel.Text     = "Name:";
            titleLabel.Width    = 50;
            titleLabel.Location = new System.Drawing.Point(5, 30);
            this.Controls.Add(titleLabel);

            //Title

            titleTB.Text     = "";
            titleTB.Width    = 165;
            titleTB.Location = new System.Drawing.Point(55, 28);
            this.Controls.Add(titleTB);

            //GroupBox
            GroupBox GB = new GroupBox();
            GB.Text      = "Apply the following setiings:";
            GB.ForeColor = System.Drawing.Color.White;
            GB.Dock      = DockStyle.Bottom;
            GB.Height    = 200;
            this.Controls.Add(GB);


            CheckBox CB = FiltersCB;
            {
                CB.Text      = "Filters";
                CB.Location  = new System.Drawing.Point(30, 20);
                CB.ForeColor = System.Drawing.Color.White;
                GB.Controls.Add(CB);
            }

            CB = SegmentationCB;
            {
                CB.Text      = "Segmentation";
                CB.Location  = new System.Drawing.Point(30, 50);
                CB.ForeColor = System.Drawing.Color.White;
                GB.Controls.Add(CB);
            }


            CB = SpotDetCB;
            {
                CB.Text      = "Spot detector";
                CB.Location  = new System.Drawing.Point(30, 80);
                CB.ForeColor = System.Drawing.Color.White;
                GB.Controls.Add(CB);
            }

            CB = TrackingCB;
            {
                CB.Text      = "Tracking";
                CB.Location  = new System.Drawing.Point(30, 110);
                CB.ForeColor = System.Drawing.Color.White;
                GB.Controls.Add(CB);
            }

            CB = ChartAxisCB;
            {
                CB.Text      = "Chart Axis";
                CB.Location  = new System.Drawing.Point(30, 140);
                CB.ForeColor = System.Drawing.Color.White;
                GB.Controls.Add(CB);
            }


            CB = TimeStepCB;
            {
                CB.Text      = "Time Intervals";
                CB.Location  = new System.Drawing.Point(30, 170);
                CB.ForeColor = System.Drawing.Color.White;
                GB.Controls.Add(CB);
            }

            //EndPanel
            Panel endP = new Panel();
            endP.Dock   = DockStyle.Bottom;
            endP.Height = 40;
            this.Controls.Add(endP);

            Button EditBtn = new Button();
            Button btn     = EditBtn;
            {
                btn.Text      = "Save";
                btn.ForeColor = System.Drawing.Color.Black;
                btn.BackColor = System.Drawing.SystemColors.ButtonFace;
                btn.Width     = 55;
                btn.Location  = new System.Drawing.Point(10, 5);
                endP.Controls.Add(btn);
                btn.Click += EditBtn_Click;
            }

            Button SaveBtn = new Button();
            btn = SaveBtn;
            {
                btn.Text      = "Save As";
                btn.ForeColor = System.Drawing.Color.Black;
                btn.BackColor = System.Drawing.SystemColors.ButtonFace;
                btn.Width     = 55;
                btn.Location  = new System.Drawing.Point(65, 5);
                endP.Controls.Add(btn);
                btn.Click += SaveBtn_Click;
            }

            Button DeleteBtn = new Button();
            btn = DeleteBtn;
            {
                btn.Text      = "Delete";
                btn.ForeColor = System.Drawing.Color.Black;
                btn.BackColor = System.Drawing.SystemColors.ButtonFace;
                btn.Width     = 55;
                btn.Location  = new System.Drawing.Point(120, 5);
                endP.Controls.Add(btn);
                btn.Click += deleteBtn_Click;
            }

            Button CancelBtn = new Button();
            btn = CancelBtn;
            {
                btn.Text      = "Cancel";
                btn.ForeColor = System.Drawing.Color.Black;
                btn.BackColor = System.Drawing.SystemColors.ButtonFace;
                btn.Width     = 55;
                btn.Location  = new System.Drawing.Point(175, 5);
                endP.Controls.Add(btn);
                btn.Click += cancelBtn_Click;
            }

            this.ResumeLayout();
            #endregion Add controls

            startBtn.Click             += startBtn_Click;
            this.FormClosing           += Form_Clossing;
            LibTB.SelectedIndexChanged += LibTB_SelectedIndexChanged;
        }
        private string calculateCTTagValue(TifFileInfo fi, ImageAnalyser IA)
        {
            List <string> vals = new List <string>();

            string val = titleTB.Text + "\t" +
                         FiltersCB.Checked.ToString() + "\t" +
                         SegmentationCB.Checked.ToString() + "\t" +
                         SpotDetCB.Checked.ToString() + "\t" +
                         TrackingCB.Checked.ToString() + "\t" +
                         fi.sizeC + "\t" +
                         ChartAxisCB.Checked.ToString() + "\t" +
                         TimeStepCB.Checked.ToString();

            vals.Add(val);

            if (FiltersCB.Checked)
            {
                vals.Add("tracking_MaxSize->" + FileEncoder.TagValueToString(fi.tracking_MaxSize));
                vals.Add("tracking_MinSize->" + FileEncoder.TagValueToString(fi.tracking_MinSize));
                vals.Add("tracking_Speed->" + FileEncoder.TagValueToString(fi.tracking_Speed));
            }

            if (SegmentationCB.Checked)
            {
                vals.Add("SegmentationProtocol->" + FileEncoder.TagValueToString(fi.SegmentationProtocol));
                vals.Add("SegmentationCBoxIndex->" + FileEncoder.TagValueToString(fi.SegmentationCBoxIndex));
                vals.Add("thresholdsCBoxIndex->" + FileEncoder.TagValueToString(fi.thresholdsCBoxIndex));
                vals.Add("RefSpotColor->" + FileEncoder.TagValueToString(fi.RefSpotColor));
                vals.Add("sumHistogramChecked->" + FileEncoder.TagValueToString(fi.sumHistogramChecked));
                vals.Add("thresholdColors->" + FileEncoder.TagValueToString(fi.thresholdColors));
                vals.Add("RefThresholdColors->" + FileEncoder.TagValueToString(fi.RefThresholdColors));
                vals.Add("thresholdValues->" + FileEncoder.TagValueToString(fi.thresholdValues));
                vals.Add("thresholds->" + FileEncoder.TagValueToString(fi.thresholds));
            }

            if (SpotDetCB.Checked)
            {
                vals.Add("SelectedSpotThresh->" + FileEncoder.TagValueToString(fi.SelectedSpotThresh));
                vals.Add("typeSpotThresh->" + FileEncoder.TagValueToString(fi.typeSpotThresh));
                vals.Add("SpotThresh->" + FileEncoder.TagValueToString(fi.SpotThresh));
                vals.Add("spotSensitivity->" + FileEncoder.TagValueToString(fi.spotSensitivity));
                vals.Add("SpotColor->" + FileEncoder.TagValueToString(fi.SpotColor));
                vals.Add("SpotTailType->" + string.Join("\t", fi.SpotTailType));
            }

            if (FiltersCB.Checked)
            {
                if (fi.newFilterHistory != null)
                {
                    vals.Add("newFilters->" + FileEncoder.TagValueToString(fi.newFilterHistory));
                }

                //vals.Add("FilterHistory->" + FileEncoder.TagValueToString(fi.FilterHistory.ToArray()));

                // if (fi.watershedList.Count!=0)
                //vals.Add("watershed->" + string.Join("\n", fi.watershedList));
            }

            if (ChartAxisCB.Checked)
            {
                vals.Add("xAxisTB->" + fi.xAxisTB.ToString());
                vals.Add("yAxisTB->" + fi.yAxisTB.ToString());
            }

            if (TimeStepCB.Checked)
            {
                vals.Add("TimeSteps->" + FileEncoder.TagValueToString(fi.TimeSteps));
            }

            return(string.Join(";\n", vals));
        }
        public static bool OpenFile(List <TabPage> Collection, string path, TabPage tp, ImageAnalyser IA, ToolStripStatusLabel StatusLabel)
        {
            StatusLabel.Text = "Reading Metadata...";

            // read metadata using ImageReader

            loci.formats.ImageReader FirstReader = new loci.formats.ImageReader();

            try
            {
                FirstReader.setId(OSStringConverter.StringToDir(path));
            }
            catch
            {
                FirstReader.close();
                StatusLabel.Text = "Ready";
                return(false);
            }

            bool isRGB = FirstReader.isRGB();

            //check is it rgb colored
            loci.formats.ChannelSeparator reader = loci.formats.ChannelSeparator.makeChannelSeparator(FirstReader);
            FirstReader = null;

            TifFileInfo fi = tp.tifFI;

            fi.seriesCount = reader.getSeriesCount();
            //Select which series to open!!!!!
            int ser = SelectSeries(reader, IA.TabPages.FileBrowser.StatusLabel);

            if (ser == -1)
            {
                fi = null;
                reader.close();
                StatusLabel.Text = "Ready";
                return(false);
            }
            else
            {
                reader.setSeries(ser);
            }
            //Check file bits per pixel - currently supported: 8 bit GrayScale, 16 bit GrayScale
            fi.bitsPerPixel = reader.getBitsPerPixel();
            if (fi.bitsPerPixel <= 8)
            {
                fi.bitsPerPixel = 8;
            }
            else if (fi.bitsPerPixel <= 16)
            {
                fi.bitsPerPixel = 16;
            }
            else
            {
                fi = null;
                reader.close();
                StatusLabel.Text = "Ready";
                return(false);
            }
            //Check is the metadata complieted and return message if not

            /*
             * if (reader.isMetadataComplete() == false)
             * {
             *  MessageBox.Show("Metadata is not complete!");
             * }
             */
            //read tags

            fi.imageCount = reader.getImageCount();
            fi.sizeX      = reader.getSizeX();
            fi.sizeY      = reader.getSizeY();
            fi.sizeZ      = reader.getSizeZ();
            fi.sizeC      = reader.getSizeC();
            fi.sizeT      = reader.getSizeT();
            //fi.dimensionOrder = reader.getDimensionOrder();
            fi.dimensionOrder              = "XYCZT";
            fi.umZ                         = 0;
            fi.umXY                        = 0;
            fi.pixelType                   = reader.getPixelType();
            fi.FalseColored                = reader.isFalseColor();
            fi.isIndexed                   = reader.isIndexed();
            fi.MetadataComplete            = reader.isMetadataComplete();
            fi.DatasetStructureDescription = reader.getDatasetStructureDescription();
            string description = getLibTifFileDescription(path);

            fi.FileDescription = string.Join("\n", new string[] { "-----------------", "CoreMetadata:\n", reader.getCoreMetadataList().ToString(),
                                                                  "-----------------", "GlobalMetadata:\n", reader.getGlobalMetadata().ToString(),
                                                                  "-----------------", "SeriesMetadata:\n", reader.getSeriesMetadata().ToString(),
                                                                  "-----------------", "FileDescription:\n", description });
            //Apply def settings
            fi.Dir       = path;
            fi.xAxisTB   = IA.chart.Properties.xAxisTB.SelectedIndex;
            fi.yAxisTB   = IA.chart.Properties.yAxisTB.SelectedIndex;
            fi.available = false;
            fi.original  = false;
            //Create LUT table
            if (isRGB)
            {
                fi.LutList = new List <Color>()
                {
                    Color.FromArgb(255, 255, 0, 0),
                    Color.FromArgb(255, 0, 255, 0),
                    Color.FromArgb(255, 0, 0, 255)
                };
            }
            else
            {
                fi.LutList = new List <Color>();
                for (int i = 0; i < fi.sizeC; i++)
                {
                    fi.LutList.Add(Color.White);
                }
            }
            //Create time steps table
            fi.TimeSteps = new List <double>();
            fi.TimeSteps.Add(fi.imageCount + 1);
            fi.TimeSteps.Add(1);

            //If its IQ3 format or Dragonflye - try to read the colors and the timesteps
            TryAndorDecoders(fi, description);

            if (fi.sizeC == 0)
            {
                fi.sizeC = 1;
            }
            if (fi.sizeZ == 0)
            {
                fi.sizeZ = 1;
            }
            if (fi.sizeT == 0)
            {
                fi.sizeT = 1;
            }

            #region Segmentation variables
            fi.SegmentationCBoxIndex = new int[fi.sizeC];
            fi.SegmentationProtocol  = new int[fi.sizeC];
            fi.thresholdsCBoxIndex   = new int[fi.sizeC];
            fi.sumHistogramChecked   = new bool[fi.sizeC];
            fi.thresholdValues       = new int[fi.sizeC][];
            fi.thresholdColors       = new Color[fi.sizeC][];
            fi.RefThresholdColors    = new Color[fi.sizeC][];
            fi.thresholds            = new int[fi.sizeC];
            fi.SpotColor             = new Color[fi.sizeC];
            fi.RefSpotColor          = new Color[fi.sizeC];
            fi.SelectedSpotThresh    = new int[fi.sizeC];
            fi.SpotThresh            = new int[fi.sizeC];
            fi.typeSpotThresh        = new int[fi.sizeC];
            fi.SpotTailType          = new string[fi.sizeC];
            fi.spotSensitivity       = new int[fi.sizeC];
            fi.roiList          = new List <ROI> [fi.sizeC];
            fi.tracking_MaxSize = new int[fi.sizeC];
            fi.tracking_MinSize = new int[fi.sizeC];
            fi.tracking_Speed   = new int[fi.sizeC];
            for (int i = 0; i < fi.sizeC; i++)
            {
                fi.sumHistogramChecked[i] = false;
                fi.thresholdValues[i]     = new int[5];
                fi.thresholdColors[i]     = new Color[]
                { Color.Transparent, Color.Transparent, Color.Transparent, Color.Transparent, Color.Transparent };
                fi.RefThresholdColors[i] = new Color[]
                { Color.Black, Color.Orange, Color.Green, Color.Blue, Color.Magenta };
                fi.SpotColor[i]        = Color.Red;
                fi.RefSpotColor[i]     = Color.Red;
                fi.SpotTailType[i]     = "<";
                fi.spotSensitivity[i]  = 100;
                fi.tracking_MaxSize[i] = 10000;
                fi.tracking_MinSize[i] = 5;
                fi.tracking_Speed[i]   = 5;
            }
            #endregion Segmentation variables

            //background worker
            var bgw = new BackgroundWorker();
            bgw.WorkerReportsProgress = true;
            bool loaded = false;
            //Add handlers to the backgroundworker
            bgw.DoWork += new DoWorkEventHandler(delegate(Object o, DoWorkEventArgs a)
            {
                //prepare array and read file
                if (isLibTifCompatible(path) && !isRGB)
                {
                    int[] dimOrder = GetFrameIndexes(reader, fi);
                    Tiff image     = Tiff.Open(OSStringConverter.StringToDir(path), "r");
                    //prepare array and read file
                    int midFrame = fi.sizeC * fi.sizeZ;
                    switch (fi.bitsPerPixel)
                    {
                    case 8:
                        fi.image8bit = new byte[image.NumberOfDirectories()][][];
                        for (int i = 0; i < midFrame; i++)
                        {
                            if (i >= fi.imageCount)
                            {
                                break;
                            }
                            IA.TabPages.myFileDecoder.Image8bit_readFrame(i, image, fi, dimOrder);
                        }
                        break;

                    case 16:
                        fi.image16bit = new ushort[image.NumberOfDirectories()][][];
                        for (int i = 0; i < midFrame; i++)
                        {
                            if (i >= fi.imageCount)
                            {
                                break;
                            }
                            IA.TabPages.myFileDecoder.Image16bit_readFrame(i, image, fi, dimOrder);
                        }
                        break;
                    }
                    loaded = true;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(0);
                    //parallel readers
                    IA.TabPages.myFileDecoder.ImageReader_BGW(Collection, image, fi, IA, path, dimOrder);
                    //report progress
                    dimOrder = null;
                    image.Close();

                    ((BackgroundWorker)o).ReportProgress(1);
                }
                else
                {
                    //Read the first T
                    byte[] buf;
                    switch (fi.bitsPerPixel)
                    {
                    case 8:
                        fi.image8bit = new byte[fi.imageCount][][];

                        buf = new byte[fi.sizeX * fi.sizeY];

                        for (int z = 0, i = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                fi.image8bit[i] = Image8bit_readFrame(
                                    reader.openBytes(
                                        reader.getIndex(z, c, 0), buf),
                                    fi.sizeX, fi.sizeY);

                                //fi.LutList[c] = ReadLut(reader);
                            }
                        }

                        break;

                    case 16:
                        fi.image16bit = new ushort[fi.imageCount][][];
                        buf           = new byte[fi.sizeX * fi.sizeY * 2];

                        for (int z = 0, i = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                fi.image16bit[i] = Image16bit_readFrame(
                                    reader.openBytes(
                                        reader.getIndex(z, c, 0), buf),
                                    fi.sizeX, fi.sizeY);

                                //fi.LutList[c] = ReadLut(reader);
                            }
                        }
                        break;
                    }
                    loaded = true;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(0);
                    //Read the rest T
                    byte[][] bigBuf = new byte[fi.imageCount][];

                    int ZCcount = fi.sizeC * fi.sizeZ;

                    for (int t = 1, i = ZCcount; t < fi.sizeT; t++)
                    {
                        for (int z = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                if (fi.image8bit != null || fi.image16bit != null)
                                {
                                    bigBuf[i] = reader.openBytes(reader.getIndex(z, c, t));
                                }
                            }
                        }
                    }
                    //Format the arrays for CellTool
                    Parallel.For(ZCcount, fi.imageCount, (int i) =>
                    {
                        try
                        {
                            switch (fi.bitsPerPixel)
                            {
                            case 8:
                                if (fi.image8bit != null)
                                {
                                    fi.image8bit[i] = Image8bit_readFrame(bigBuf[i],
                                                                          fi.sizeX, fi.sizeY);
                                }
                                bigBuf[i] = null;
                                break;

                            case 16:
                                if (fi.image16bit != null)
                                {
                                    fi.image16bit[i] = Image16bit_readFrame(bigBuf[i],
                                                                            fi.sizeX, fi.sizeY);
                                }
                                bigBuf[i] = null;
                                break;
                            }
                        }
                        catch { }
                    });
                    bigBuf = null;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(1);
                }
            });
            bgw.ProgressChanged += new ProgressChangedEventHandler(delegate(Object o, ProgressChangedEventArgs a)
            {
                if (a.ProgressPercentage == 0)
                {
                    fi.openedImages = fi.sizeC * fi.sizeZ;
                    try
                    {
                        IA.ReloadImages();
                    }
                    catch { }
                }
                else if (a.ProgressPercentage == 1)
                {
                    //dispose the reader
                    reader.close();
                    reader = null;
                    //mark as loaded
                    fi.openedImages = fi.imageCount;
                    fi.available    = true;
                    fi.loaded       = true;

                    IA.TabPages.myFileDecoder.CalculateAllRois(fi);

                    IA.ReloadImages();
                    bool check = true;
                    foreach (TabPage tp1 in Collection)
                    {
                        if (tp1.tifFI != null && tp1.tifFI.available == false)
                        {
                            check = false;
                            break;
                        }
                    }
                    if (check == true)
                    {
                        IA.TabPages.myFileDecoder.loadingTimer.Stop();
                        StatusLabel.Text = "Ready";
                    }

                    if (IA.Segmentation.AutoSetUp.LibTB.SelectedIndex > 0 &&
                        IA.Segmentation.AutoSetUp.ApplyToNewCheckB.Checked &&
                        MessageBox.Show("Do you want to open the image with the following protocol:\n" +
                                        IA.Segmentation.AutoSetUp.LibTB.Text,
                                        "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        IA.Segmentation.AutoSetUp.ApplyCT3Tags(IA.Segmentation.AutoSetUp.protocols[
                                                                   IA.Segmentation.AutoSetUp.LibTB.SelectedIndex].Split(
                                                                   new string[] { ";\n" }, StringSplitOptions.None), fi);
                    }
                }
            });

            //Start background worker
            StatusLabel.Text = "Reading Image...";
            //Clear OldImage
            IA.IDrawer.ClearImage();

            //start bgw
            bgw.RunWorkerAsync();
            //add taskbar
            tp.tifFI.tpTaskbar.Initialize(IA.TabPages.ImageMainPanel, IA, fi);

            try
            {
                if (loaded == true)
                {
                    IA.ReloadImages();
                }
            }
            catch { }
            //out put
            return(true);
        }
        private static void SaveTif_8bitRawData(TifFileInfo fi, string fileName, ImageAnalyser IA)
        {
            // Register the extender callback
            m_parentExtender = Tiff.SetTagExtender(TagExtender);
            string value = calculateCTTagValue(fi, IA);

            int numberOfPages = fi.imageCount;

            int width           = fi.sizeX;
            int height          = fi.sizeY;
            int samplesPerPixel = 1;
            int bitsPerSample   = fi.bitsPerPixel;

            //check the size of the image and start the writer
            int writersCount = NumberOfTiffWriters(fi);

            if (writersCount == 1)
            {
                using (Tiff output = Tiff.Open(fileName, "w"))
                {
                    for (int page = 0; page < numberOfPages; page++)
                    {
                        byte[][] firstPageBuffer = fi.image8bit[page];
                        output.SetField(TiffTag.IMAGELENGTH, height);
                        output.SetField(TiffTag.IMAGEWIDTH, width);
                        output.SetField(TiffTag.SAMPLESPERPIXEL, samplesPerPixel);
                        output.SetField(TiffTag.BITSPERSAMPLE, bitsPerSample);
                        output.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                        output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                        output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                        output.SetField(TiffTag.ROWSPERSTRIP, output.DefaultStripSize(0));
                        output.SetField(TiffTag.COMPRESSION, Compression.NONE);
                        output.SetField(TiffTag.IMAGEDESCRIPTION, ImageDetails());
                        // specify that it's a page within the multipage file
                        output.SetField(TiffTag.SUBFILETYPE, FileType.PAGE);
                        // specify the page number
                        output.SetField(TiffTag.PAGENUMBER, page, numberOfPages);

                        if (page == numberOfPages - 1)
                        {
                            // set the custom tag
                            output.SetField(TIFFTAG_CellTool_METADATA, value);
                        }
                        for (int j = 0; j < height; ++j)
                        {
                            output.WriteScanline(firstPageBuffer[j], j);
                        }

                        output.WriteDirectory();
                    }
                }
            }
            else
            {
                string newFileName = CheckForFileChain(fileName);               //Remove time chain suffix
                newFileName = newFileName.Substring(0, newFileName.Length - 4); //remove .tif extension

                int pageMaxPerWriter = NumberOfFramesPerPart(fi);               //get maximal pages per writer

                fi.Dir = FileChain_GetName(0, newFileName);                     //set the filename to the first file from the chain

                Parallel.For(0, writersCount, (ind) =>
                {
                    int start = ind * pageMaxPerWriter;
                    int stop  = start + pageMaxPerWriter;
                    using (Tiff output = Tiff.Open(FileChain_GetName(ind, newFileName), "w"))
                    {
                        for (int page = 0; start < numberOfPages && start < stop; page++, start++)
                        {
                            byte[][] firstPageBuffer = fi.image8bit[start];
                            output.SetField(TiffTag.IMAGELENGTH, height);
                            output.SetField(TiffTag.IMAGEWIDTH, width);
                            output.SetField(TiffTag.SAMPLESPERPIXEL, samplesPerPixel);
                            output.SetField(TiffTag.BITSPERSAMPLE, bitsPerSample);
                            output.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                            output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                            output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                            output.SetField(TiffTag.ROWSPERSTRIP, output.DefaultStripSize(0));
                            output.SetField(TiffTag.COMPRESSION, Compression.NONE);
                            output.SetField(TiffTag.IMAGEDESCRIPTION, ImageDetails());
                            // specify that it's a page within the multipage file
                            output.SetField(TiffTag.SUBFILETYPE, FileType.PAGE);
                            // specify the page number
                            output.SetField(TiffTag.PAGENUMBER, page, pageMaxPerWriter);

                            if (start == numberOfPages - 1 || start == stop - 1)
                            {
                                // set the custom tag
                                output.SetField(TIFFTAG_CellTool_METADATA, value);
                            }
                            for (int j = 0; j < height; ++j)
                            {
                                output.WriteScanline(firstPageBuffer[j], j);
                            }

                            output.WriteDirectory();
                        }
                    }
                });
            }
            // restore previous tag extender
            Tiff.SetTagExtender(m_parentExtender);
        }
        private static string calculateCTTagValue(TifFileInfo fi, ImageAnalyser IA)
        {
            List <string> vals = new List <string>();

            vals.Add("seriesCount->" + fi.seriesCount.ToString());
            vals.Add("imageCount->" + fi.imageCount.ToString());
            vals.Add("sizeX->" + fi.sizeX.ToString());
            vals.Add("sizeY->" + fi.sizeY.ToString());
            vals.Add("sizeC->" + fi.sizeC.ToString());
            vals.Add("sizeZ->" + fi.sizeZ.ToString());
            vals.Add("sizeT->" + fi.sizeT.ToString());
            vals.Add("umXY->" + fi.umXY.ToString());
            vals.Add("umZ->" + fi.umZ.ToString());
            vals.Add("bitsPerPixel->" + fi.bitsPerPixel.ToString());
            vals.Add("dimensionOrder->" + fi.dimensionOrder);
            vals.Add("pixelType->" + fi.pixelType.ToString());
            vals.Add("FalseColored->" + fi.FalseColored.ToString());
            vals.Add("isIndexed->" + fi.isIndexed.ToString());
            vals.Add("MetadataComplete->" + fi.MetadataComplete.ToString());
            vals.Add("DatasetStructureDescription->" + fi.DatasetStructureDescription);
            vals.Add("Micropoint->" + fi.Micropoint.ToString());
            vals.Add("autoDetectBandC->" + fi.autoDetectBandC.ToString());
            vals.Add("applyToAllBandC->" + fi.applyToAllBandC.ToString());
            vals.Add("xCompensation->" + fi.xCompensation.ToString());
            vals.Add("yCompensation->" + fi.yCompensation.ToString());
            vals.Add("DataSourceInd->" + fi.DataSourceInd.ToString());
            vals.Add("LutList->" + TagValueToString(fi.LutList));
            vals.Add("TimeSteps->" + TagValueToString(fi.TimeSteps));
            vals.Add("MinBrightness->" + TagValueToString(fi.MinBrightness));
            vals.Add("MaxBrightness->" + TagValueToString(fi.MaxBrightness));
            vals.Add("tracking_MaxSize->" + TagValueToString(fi.tracking_MaxSize));
            vals.Add("tracking_MinSize->" + TagValueToString(fi.tracking_MinSize));
            vals.Add("tracking_Speed->" + TagValueToString(fi.tracking_Speed));
            vals.Add("SegmentationProtocol->" + TagValueToString(fi.SegmentationProtocol));
            vals.Add("SegmentationCBoxIndex->" + TagValueToString(fi.SegmentationCBoxIndex));
            vals.Add("thresholdsCBoxIndex->" + TagValueToString(fi.thresholdsCBoxIndex));
            vals.Add("SelectedSpotThresh->" + TagValueToString(fi.SelectedSpotThresh));
            vals.Add("typeSpotThresh->" + TagValueToString(fi.typeSpotThresh));
            vals.Add("SpotThresh->" + TagValueToString(fi.SpotThresh));
            vals.Add("spotSensitivity->" + TagValueToString(fi.spotSensitivity));
            vals.Add("thresholds->" + TagValueToString(fi.thresholds));
            vals.Add("SpotColor->" + TagValueToString(fi.SpotColor));
            vals.Add("RefSpotColor->" + TagValueToString(fi.RefSpotColor));
            vals.Add("sumHistogramChecked->" + TagValueToString(fi.sumHistogramChecked));
            vals.Add("SpotTailType->" + string.Join("\t", fi.SpotTailType));
            vals.Add("thresholdColors->" + TagValueToString(fi.thresholdColors));
            vals.Add("RefThresholdColors->" + TagValueToString(fi.RefThresholdColors));
            vals.Add("thresholdValues->" + TagValueToString(fi.thresholdValues));
            vals.Add("FileDescription->" + fi.FileDescription.Replace(";", ".").Replace("->", ": "));
            vals.Add("xAxisTB->" + fi.xAxisTB.ToString());
            vals.Add("yAxisTB->" + fi.yAxisTB.ToString());
            if (fi.yAxisTB >= 5)
            {
                vals.Add("yFormula->" + IA.chart.Properties.GetFunction(fi.yAxisTB).Replace(";", ""));
            }

            //Roi part
            int c = 0;

            foreach (List <ROI> roiList in fi.roiList)
            {
                if (roiList != null)
                {
                    foreach (ROI roi in roiList)
                    {
                        vals.Add("roi.new->" + IA.RoiMan.roi_new(c, roi));
                    }
                }
                c++;
            }

            //it is important FilterHistory to be the last
            //vals.Add("FilterHistory->" + TagValueToString(fi.FilterHistory.ToArray()));

            //if (fi.watershedList.Count != 0)
            //vals.Add("watershed->" + string.Join("\n", fi.watershedList));

            if (fi.newFilterHistory != null)
            {
                vals.Add("newFilters->" + TagValueToString(fi.newFilterHistory));
            }

            return(string.Join(";\n", vals));
        }
Example #13
0
        private static loci.formats.ChannelSeparator ReadMetadata(string path, List <TabPage> Collection, TabPage tp, ImageAnalyser IA)
        {
            // read metadata using ImageReader
            loci.formats.ImageReader FirstReader = new loci.formats.ImageReader();
            try
            {
                FirstReader.setId(path);
            }
            catch
            {
                FirstReader.close();
                IA.FileBrowser.StatusLabel.Text = "Ready";
                return(null);
            }

            bool isRGB = FirstReader.isRGB();

            //check is it rgb colored
            loci.formats.ChannelSeparator reader = loci.formats.ChannelSeparator.makeChannelSeparator(FirstReader);
            FirstReader = null;

            TifFileInfo fi = tp.tifFI;

            fi.seriesCount = reader.getSeriesCount();
            //Select which series to open!!!!!
            int ser = SelectSeries(reader);

            if (ser == -1)
            {
                fi = null;
                reader.close();
                IA.FileBrowser.StatusLabel.Text = "Ready";
                return(null);
            }
            else
            {
                reader.setSeries(ser);
            }
            //Check file bits per pixel - currently supported: 8 bit GrayScale, 16 bit GrayScale
            fi.bitsPerPixel = reader.getBitsPerPixel();
            if (fi.bitsPerPixel <= 8)
            {
                fi.bitsPerPixel = 8;
            }
            else if (fi.bitsPerPixel <= 16)
            {
                fi.bitsPerPixel = 16;
            }
            else
            {
                fi = null;
                reader.close();
                IA.FileBrowser.StatusLabel.Text = "Ready";
                return(null);
            }
            //Check is the metadata complieted and return message if not

            /*
             * if (reader.isMetadataComplete() == false)
             * {
             *  MessageBox.Show("Metadata is not complete!");
             * }
             */
            //read tags

            fi.imageCount = reader.getImageCount();
            fi.sizeX      = reader.getSizeX();
            fi.sizeY      = reader.getSizeY();
            fi.sizeZ      = reader.getSizeZ();
            fi.sizeC      = reader.getSizeC();
            fi.sizeT      = reader.getSizeT();
            //fi.dimensionOrder = reader.getDimensionOrder();
            fi.dimensionOrder              = "XYCZT";
            fi.umZ                         = 0;
            fi.umXY                        = 0;
            fi.pixelType                   = reader.getPixelType();
            fi.FalseColored                = reader.isFalseColor();
            fi.isIndexed                   = reader.isIndexed();
            fi.MetadataComplete            = reader.isMetadataComplete();
            fi.DatasetStructureDescription = reader.getDatasetStructureDescription();
            string description = getLibTifFileDescription(path);

            fi.FileDescription = string.Join("\n", new string[] { "-----------------", "CoreMetadata:\n", reader.getCoreMetadataList().ToString(),
                                                                  "-----------------", "GlobalMetadata:\n", reader.getGlobalMetadata().ToString(),
                                                                  "-----------------", "SeriesMetadata:\n", reader.getSeriesMetadata().ToString(),
                                                                  "-----------------", "FileDescription:\n", description });
            //Apply def settings
            fi.Dir       = path;
            fi.xAxisTB   = IA.chart.Properties.xAxisTB.SelectedIndex;
            fi.yAxisTB   = IA.chart.Properties.yAxisTB.SelectedIndex;
            fi.available = false;
            fi.original  = false;
            //Create LUT table
            if (isRGB)
            {
                fi.LutList = new List <Color>()
                {
                    Color.FromArgb(255, 255, 0, 0),
                    Color.FromArgb(255, 0, 255, 0),
                    Color.FromArgb(255, 0, 0, 255)
                };
            }
            else
            {
                fi.LutList = new List <Color>();
                for (int i = 0; i < fi.sizeC; i++)
                {
                    fi.LutList.Add(Color.White);
                }
            }
            //Create time steps table
            fi.TimeSteps = new List <double>();
            fi.TimeSteps.Add(fi.imageCount + 1);
            fi.TimeSteps.Add(1);

            //If its IQ3 format or Dragonflye - try to read the colors and the timesteps
            TryAndorDecoders(fi, description);

            if (fi.sizeC == 0)
            {
                fi.sizeC = 1;
            }
            if (fi.sizeZ == 0)
            {
                fi.sizeZ = 1;
            }
            if (fi.sizeT == 0)
            {
                fi.sizeT = 1;
            }

            #region Segmentation variables
            fi.SegmentationCBoxIndex = new int[fi.sizeC];
            fi.SegmentationProtocol  = new int[fi.sizeC];
            fi.thresholdsCBoxIndex   = new int[fi.sizeC];
            fi.sumHistogramChecked   = new bool[fi.sizeC];
            fi.thresholdValues       = new int[fi.sizeC][];
            fi.thresholdColors       = new Color[fi.sizeC][];
            fi.RefThresholdColors    = new Color[fi.sizeC][];
            fi.thresholds            = new int[fi.sizeC];
            fi.SpotColor             = new Color[fi.sizeC];
            fi.RefSpotColor          = new Color[fi.sizeC];
            fi.SelectedSpotThresh    = new int[fi.sizeC];
            fi.SpotThresh            = new int[fi.sizeC];
            fi.typeSpotThresh        = new int[fi.sizeC];
            fi.SpotTailType          = new string[fi.sizeC];
            fi.spotSensitivity       = new int[fi.sizeC];
            fi.roiList          = new List <ROI> [fi.sizeC];
            fi.tracking_MaxSize = new int[fi.sizeC];
            fi.tracking_MinSize = new int[fi.sizeC];
            fi.tracking_Speed   = new int[fi.sizeC];
            for (int i = 0; i < fi.sizeC; i++)
            {
                fi.sumHistogramChecked[i] = false;
                fi.thresholdValues[i]     = new int[5];
                fi.thresholdColors[i]     = new Color[]
                { Color.Transparent, Color.Transparent, Color.Transparent, Color.Transparent, Color.Transparent };
                fi.RefThresholdColors[i] = new Color[]
                { Color.Black, Color.Orange, Color.Green, Color.Blue, Color.Magenta };
                fi.SpotColor[i]        = Color.Red;
                fi.RefSpotColor[i]     = Color.Red;
                fi.SpotTailType[i]     = "<";
                fi.spotSensitivity[i]  = 100;
                fi.tracking_MaxSize[i] = 10000;
                fi.tracking_MinSize[i] = 5;
                fi.tracking_Speed[i]   = 5;
            }
            #endregion Segmentation variables
            return(reader);
        }
 /// <summary>
 /// Initializes this class
 /// </summary>
 private void Awake()
 {
     // Allows this instance to behave like a singleton
     Instance = this;
 }
Example #15
0
        public void Initialize(Panel MainPanel, ImageAnalyser IA1, TifFileInfo tifFI1)
        {
            tifFI = tifFI1;
            IA    = IA1;

            int w = 30;
            int h = 30;

            TopBar.Width  = MainPanel.Width - w;
            TopBar.Height = h;
            TopBar.Dock   = DockStyle.Top;
            //MainPanel.Controls.Add(TopBar);
            IA.IDrawer.corePanel.Height = TopBar.Height;
            IA.IDrawer.corePanel.Controls.Add(TopBar);
            TopBar.BringToFront();

            ColorPanel.Dock      = DockStyle.Right;
            ColorPanel.BackColor = IA.FileBrowser.BackGround2Color1;
            TopBar.Controls.Add(ColorPanel);
            ColorPanel.BringToFront();

            XYValPanel.Controls.Add(XLabel);
            XLabel.Font     = new Font(XLabel.Font.Name, 6.9F);
            XLabel.Location = new Point(0, 15);
            XLabel.Text     = "X: 10000";
            XLabel.Visible  = false;
            XLabel.Width    = 45;

            XYValPanel.Controls.Add(YLabel);
            YLabel.Font     = new Font(XLabel.Font.Name, 6.9F);
            YLabel.Location = new Point(47, 15);
            YLabel.Text     = "Y: 10000";
            YLabel.Visible  = false;
            YLabel.Width    = 45;

            XYValPanel.Controls.Add(ValLabel);
            ValLabel.Font     = new Font(XLabel.Font.Name, 6.9F);
            ValLabel.Location = new Point(94, 15);
            ValLabel.Text     = "Value: 10000";
            ValLabel.Width    = 70;
            ValLabel.Visible  = false;

            XYValPanel.Dock      = DockStyle.Right;
            XYValPanel.Width     = 165;
            XYValPanel.BackColor = IA.FileBrowser.BackGroundColor1;
            TopBar.Controls.Add(XYValPanel);
            XYValPanel.BringToFront();

            Panel SmallColorPanel = new Panel();

            SmallColorPanel.BackColor = IA.FileBrowser.BackGroundColor1;
            SmallColorPanel.Dock      = DockStyle.Top;
            SmallColorPanel.Height    = 5;
            ColorPanel.Controls.Add(SmallColorPanel);

            MethodsPanel.Dock      = DockStyle.Left;
            MethodsPanel.BackColor = IA.FileBrowser.BackGroundColor1;
            MethodsPanel.Width     = 100;
            TopBar.Controls.Add(MethodsPanel);
            MethodsPanel.BringToFront();

            Refresh();

            VisualizeColorBtns();
            VisualizeMethodsBtns();
        }
Example #16
0
 public MyWatershed(ImageAnalyser IA)
 {
     this.IA = IA;
     createDialog();
 }
Example #17
0
 public CTChart(ImageAnalyser IA)
 {
     this.IA = IA;
 }
Example #18
0
 public KMeansSegmentation(ImageAnalyser IA)
 {
     this.IA = IA;
 }
Example #19
0
        private static bool SubstackToolStripMenuItem_click(string path, List <TabPage> Collection, TabPage tp, ImageAnalyser IA, loci.formats.ChannelSeparator reader, int[][] dim)
        {
            TifFileInfo fi = tp.tifFI;

            if (dim == null)
            {
                return(false);
            }
            ////////
            /////background worker
            bool loaded = false;
            //Add handlers to the backgroundworker
            var bgw = new BackgroundWorker();

            bgw.WorkerReportsProgress = true;

            TifFileInfo newFI = null;

            //Add event for projection here
            bgw.DoWork += new DoWorkEventHandler(delegate(Object o, DoWorkEventArgs a)
            {
                //Prepare matrix
                int T, Z, C, f = 0,
                curT, curZ, curC;
                List <int> matrix = new List <int>();
                for (T = 0, curT = dim[0][0] - 1; T < fi.sizeT; T++)
                {
                    if (T == curT && T < dim[0][1])
                    {
                        for (Z = 0, curZ = dim[1][0] - 1; Z < fi.sizeZ; Z++)
                        {
                            if (Z == curZ && Z < dim[1][1])
                            {
                                for (C = 0, curC = dim[2][0] - 1; C < fi.sizeC; C++, f++)
                                {
                                    if (C == curC && C < dim[2][1])
                                    {
                                        //matrix.Add(f);
                                        matrix.Add(reader.getIndex(Z, C, T));
                                        curC += dim[2][2];
                                    }
                                }

                                curZ += dim[1][2];
                            }
                            else
                            {
                                f += fi.sizeC;
                            }
                        }

                        curT += dim[0][2];
                    }
                    else
                    {
                        f += fi.sizeC * fi.sizeZ;
                    }
                }

                newFI     = fi;
                newFI.Dir = newFI.Dir.Substring(0, newFI.Dir.LastIndexOf(".")) +
                            "_Substack.tif";

                newFI.sizeT = 0;
                for (int i = dim[0][0] - 1; i < dim[0][1]; i += dim[0][2])
                {
                    newFI.sizeT++;
                }

                newFI.sizeZ = 0;
                for (int i = dim[1][0] - 1; i < dim[1][1]; i += dim[1][2])
                {
                    newFI.sizeZ++;
                }

                newFI.sizeC          = 0;
                List <Color> colList = new List <Color>();
                for (int i = dim[2][0] - 1; i < dim[2][1]; i += dim[2][2])
                {
                    newFI.sizeC++;
                    colList.Add(fi.LutList[i]);
                }

                newFI.imageCount   = matrix.Count;
                newFI.openedImages = matrix.Count;
                AddEmptyArraysToFI(newFI);
                newFI.LutList = colList;

                //read image

                //Read the first T
                //prepare array and read file
                if (isLibTifCompatible(path) && !reader.isRGB())
                {
                    int[] dimOrder = matrix.ToArray();
                    Tiff image     = Tiff.Open(path, "r");
                    //prepare array and read file
                    int midFrame = fi.sizeC * fi.sizeZ;
                    switch (fi.bitsPerPixel)
                    {
                    case 8:
                        fi.image8bit = new byte[fi.imageCount][][];
                        for (int i = 0; i < midFrame; i++)
                        {
                            if (i >= fi.imageCount)
                            {
                                break;
                            }
                            IA.TabPages.myFileDecoder.Image8bit_readFrame(i, image, fi, dimOrder);
                        }
                        break;

                    case 16:
                        fi.image16bit = new ushort[fi.imageCount][][];
                        for (int i = 0; i < midFrame; i++)
                        {
                            if (i >= fi.imageCount)
                            {
                                break;
                            }
                            IA.TabPages.myFileDecoder.Image16bit_readFrame(i, image, fi, dimOrder);
                        }
                        break;
                    }
                    loaded = true;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(0);
                    //parallel readers
                    IA.TabPages.myFileDecoder.ImageReader_BGW(Collection, image, fi, IA, path, dimOrder);
                    //report progress
                    dimOrder = null;
                    image.Close();

                    ((BackgroundWorker)o).ReportProgress(1);
                }
                else
                {
                    byte[] buf;
                    switch (fi.bitsPerPixel)
                    {
                    case 8:
                        fi.image8bit = new byte[fi.imageCount][][];

                        buf = new byte[fi.sizeX * fi.sizeY];

                        for (int z = 0, i = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                fi.image8bit[i] = Image8bit_readFrame(
                                    reader.openBytes(
                                        matrix[i], buf),
                                    fi.sizeX, fi.sizeY);

                                //fi.LutList[c] = ReadLut(reader);
                            }
                        }

                        break;

                    case 16:
                        fi.image16bit = new ushort[fi.imageCount][][];
                        buf           = new byte[fi.sizeX * fi.sizeY * 2];

                        for (int z = 0, i = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                fi.image16bit[i] = Image16bit_readFrame(
                                    reader.openBytes(
                                        matrix[i], buf),
                                    fi.sizeX, fi.sizeY);

                                //fi.LutList[c] = ReadLut(reader);
                            }
                        }
                        break;
                    }
                    loaded = true;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(0);
                    //Read the rest T
                    byte[][] bigBuf = new byte[fi.imageCount][];

                    int ZCcount = fi.sizeC * fi.sizeZ;

                    for (int t = 1, i = ZCcount; t < fi.sizeT; t++)
                    {
                        for (int z = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                if (fi.image8bit != null || fi.image16bit != null)
                                {
                                    bigBuf[i] = reader.openBytes(matrix[i]);
                                }
                            }
                        }
                    }
                    //Format the arrays for CellTool
                    Parallel.For(ZCcount, fi.imageCount, (int i) =>
                    {
                        try
                        {
                            switch (fi.bitsPerPixel)
                            {
                            case 8:
                                if (fi.image8bit != null)
                                {
                                    fi.image8bit[i] = Image8bit_readFrame(bigBuf[i],
                                                                          fi.sizeX, fi.sizeY);
                                }
                                bigBuf[i] = null;
                                break;

                            case 16:
                                if (fi.image16bit != null)
                                {
                                    fi.image16bit[i] = Image16bit_readFrame(bigBuf[i],
                                                                            fi.sizeX, fi.sizeY);
                                }
                                bigBuf[i] = null;
                                break;
                            }
                        }
                        catch { }
                    });
                    bigBuf = null;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(1);
                }
            });
            bgw.ProgressChanged += new ProgressChangedEventHandler(delegate(Object o, ProgressChangedEventArgs a)
            {
                if (a.ProgressPercentage == 0)
                {
                    fi.openedImages = fi.sizeC * fi.sizeZ;
                    try
                    {
                        IA.ReloadImages();
                    }
                    catch { }
                }
                else if (a.ProgressPercentage == 1)
                {
                    //dispose the reader
                    reader.close();
                    reader = null;
                    //mark as loaded
                    fi.openedImages = fi.imageCount;
                    fi.available    = true;
                    fi.loaded       = true;
                    newFI.original  = false;

                    IA.TabPages.myFileDecoder.CalculateAllRois(fi);

                    IA.ReloadImages();
                    bool check = true;
                    foreach (TabPage tp1 in Collection)
                    {
                        if (tp1.tifFI != null && tp1.tifFI.available == false)
                        {
                            check = false;
                            break;
                        }
                    }
                    if (check == true)
                    {
                        IA.TabPages.myFileDecoder.loadingTimer.Stop();
                        IA.FileBrowser.StatusLabel.Text = "Ready";
                    }

                    if (IA.Segmentation.AutoSetUp.LibTB.SelectedIndex > 0 &&
                        IA.Segmentation.AutoSetUp.ApplyToNewCheckB.Checked &&
                        MessageBox.Show("Do you want to open the image with the following protocol:\n" +
                                        IA.Segmentation.AutoSetUp.LibTB.Text,
                                        "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        IA.Segmentation.AutoSetUp.ApplyCT3Tags(IA.Segmentation.AutoSetUp.protocols[
                                                                   IA.Segmentation.AutoSetUp.LibTB.SelectedIndex].Split(
                                                                   new string[] { ";\n" }, StringSplitOptions.None), fi);
                    }
                }
            });

            //Start background worker
            IA.FileBrowser.StatusLabel.Text = "Reading Image...";
            //Clear OldImage
            IA.IDrawer.ClearImage();

            //start bgw
            bgw.RunWorkerAsync();
            //add taskbar
            tp.tifFI.tpTaskbar.Initialize(IA.TabPages.ImageMainPanel, IA, fi);

            try
            {
                if (loaded == true)
                {
                    IA.ReloadImages();
                }
            }
            catch { }
            //output
            return(true);
        }
Example #20
0
        /// <summary>
        /// Check the file size and if there is no avaliable RAM - open only a fragment of the image
        /// </summary>
        /// <param name="path"></param>
        /// <param name="Collection"></param>
        /// <param name="tp"></param>
        /// <param name="IA1"></param>
        /// <returns></returns>
        public static bool OpenBigImage(string path, List <TabPage> Collection, TabPage tp, ImageAnalyser IA)
        {
            //Check the file size in bytes
            long FileSize = new System.IO.FileInfo(path).Length;
            //Check the free ram memory in bytes
            long RAM = (long)new ComputerInfo().AvailablePhysicalMemory;

            // RAM = 10000000;
            if (FileSize < RAM)
            {
                return(false);
            }
            else
            {
                loci.formats.ChannelSeparator reader;
                //read file metadata
                try
                {
                    reader = ReadMetadata(path, Collection, tp, IA);
                }
                catch
                {
                    MessageBox.Show("Error: Not avaliable file format!");
                    IA.FileBrowser.StatusLabel.Text = "Ready";
                    return(false);
                }

                if (reader == null)
                {
                    MessageBox.Show("Error: Not avaliable file format!");
                    IA.FileBrowser.StatusLabel.Text = "Ready";
                    return(false);
                }

                //get new file dimentions
                int[][] matrix = null;
                while (!CheckSize(RAM, matrix, tp.tifFI))
                {
                    matrix = SubstackDialog(tp.tifFI);

                    if (matrix == null)
                    {
                        reader.close();
                        reader = null;
                        IA.FileBrowser.StatusLabel.Text = "Ready";
                        return(false);
                    }
                }

                return(SubstackToolStripMenuItem_click(path, Collection, tp, IA, reader, matrix));
            }
        }
 public Ncalc_Adapter(ImageAnalyser IA)
 {
     this.IA = IA;
 }
Example #22
0
        public SpotDetector(Panel mainPanel, ImageAnalyser IA)
        {
            this.IA = IA;

            Panel p1 = new Panel();

            p1.Height = 5;
            p1.Dock   = DockStyle.Top;
            mainPanel.Controls.Add(p1);
            p1.BringToFront();

            #region Threshold
            {
                CTTrackBar tb = new CTTrackBar();
                tb.Initialize();
                tb.Panel.Dock = DockStyle.Top;
                tb.BackColor(IA.FileBrowser.BackGround2Color1);
                tb.ForeColor(IA.FileBrowser.ShriftColor1);
                tb.Panel.Visible = true;
                tb.Refresh(0, 0, 10);
                tb.Name.Text       = "Threshold:";
                tb.NamePanel.Width = 62;
                mainPanel.Controls.Add(tb.Panel);
                thresh = tb;
                tb.Panel.BringToFront();
                tb.Value.Changed += new ChangedValueEventHandler(delegate(Object o, ChangeValueEventArgs a)
                {
                    thresh_valueChange(int.Parse(a.Value));
                });
            }
            #endregion Threshold

            #region Options
            {
                CTTrackBar tb = new CTTrackBar();
                tb.Initialize();
                tb.Panel.Dock = DockStyle.Top;
                tb.BackColor(IA.FileBrowser.BackGround2Color1);
                tb.ForeColor(IA.FileBrowser.ShriftColor1);
                tb.Panel.Visible = true;
                tb.Refresh(100, 1, 100);
                tb.Name.Text       = "Sensitivity:";
                tb.NamePanel.Width = 62;
                mainPanel.Controls.Add(tb.Panel);
                sensitivity = tb;
                tb.Panel.BringToFront();
                tb.Value.Changed += new ChangedValueEventHandler(delegate(Object o, ChangeValueEventArgs a)
                {
                    sensitivity_valueChange(int.Parse(a.Value));
                });
            }

            Panel p = new Panel();
            p.Height = 30;
            p.Dock   = DockStyle.Top;
            mainPanel.Controls.Add(p);
            p.BringToFront();

            //Thresh list box
            selectT.Tag      = "Select Threshold";
            selectT.Width    = 60;
            selectT.Location = new Point(53, 1);
            selectT.Items.Add("None");
            selectT.DropDownStyle = ComboBoxStyle.DropDownList;
            selectT.SelectedIndex = 0;
            selectT.AutoSize      = false;
            p.Controls.Add(selectT);
            selectT.BringToFront();
            selectT.MouseHover           += Control_MouseOver;
            selectT.SelectedIndexChanged += selectT_IndexChange;

            //ThreshType box
            tType.Tag      = "Set threshold type";
            tType.Width    = 60;
            tType.Location = new Point(120, 1);
            tType.Items.AddRange(new string[] { "Pixels", "% Max" });
            tType.DropDownStyle = ComboBoxStyle.DropDownList;
            tType.SelectedIndex = 0;
            tType.AutoSize      = false;
            p.Controls.Add(tType);
            tType.BringToFront();
            tType.MouseHover           += Control_MouseOver;
            tType.SelectedIndexChanged += TType_IndexChange;
            //Color btn
            {
                Button btn = new Button();
                ColBtn = btn;

                btn.FlatStyle = FlatStyle.Flat;
                btn.FlatAppearance.BorderSize = 0;
                btn.BackColor = Color.Red;
                btn.ForeColor = Color.Black;
                btn.Location  = new Point(3, 1);
                btn.Text      = "";
                btn.Tag       = "Select color for the spots";
                btn.Height    = 22;
                btn.Width     = 25;
                p.Controls.Add(btn);
                btn.BringToFront();
                btn.Visible     = true;
                btn.MouseHover += Control_MouseOver;
                btn.MouseDown  += ColBtn_Click;
            }
            //<>btn
            {
                Button btn = new Button();
                TailType = btn;

                btn.FlatStyle = FlatStyle.Flat;
                btn.FlatAppearance.BorderSize = 0;
                btn.ForeColor = Color.White;
                btn.Location  = new Point(28, 1);
                btn.Text      = ">";
                btn.Tag       = "Set spot intensity diapason";
                btn.Height    = 22;
                btn.Width     = 25;
                p.Controls.Add(btn);
                btn.BringToFront();
                btn.Visible     = true;
                btn.MouseHover += Control_MouseOver;
                btn.Click      += TailType_Click;
            }

            #endregion Options
        }
Example #23
0
        public OtsuSegmentation(Panel mainPanel, ImageAnalyser IA)
        {
            this.IA = IA;
            //Core panel
            panel.Dock      = DockStyle.Top;
            panel.BackColor = IA.FileBrowser.BackGround2Color1;
            panel.ForeColor = IA.FileBrowser.ShriftColor1;
            panel.Visible   = false;
            panel.Height    = 150;
            mainPanel.Controls.Add(panel);
            panel.BringToFront();

            #region Options
            GroupBox optionGB = new GroupBox();
            optionGB.Text      = "Options:";
            optionGB.BackColor = IA.FileBrowser.BackGround2Color1;
            optionGB.ForeColor = IA.FileBrowser.ShriftColor1;
            optionGB.Dock      = DockStyle.Top;
            optionGB.Height    = 85;
            panel.Controls.Add(optionGB);
            optionGB.BringToFront();

            Label Name = new Label();
            Name.Text     = "Thresholds:";
            Name.Width    = TextRenderer.MeasureText(Name.Text, Name.Font).Width;
            Name.Location = new Point(5, 18);
            optionGB.Controls.Add(Name);
            Name.BringToFront();

            ComboBox cb = thresholdsNumCB;
            cb.Text = "0";
            cb.Items.AddRange(new string[] { "0", "1", "2", "3", "4" });
            cb.Width    = 40;
            cb.Location = new Point(80, 15);
            optionGB.Controls.Add(cb);
            cb.BringToFront();
            cb.DropDownStyle         = ComboBoxStyle.DropDownList;
            cb.SelectedIndex         = 0;
            cb.AutoSize              = false;
            cb.SelectedIndexChanged += new EventHandler(delegate(object o, EventArgs e)
            {
                TifFileInfo fi = IA.TabPages.TabCollections[IA.TabPages.SelectedIndex].tifFI;
                fi.thresholdsCBoxIndex[fi.cValue] = cb.SelectedIndex;
                IA.ReloadImages();
            });

            CheckBox checkB = sumHistogramsCheckBox;
            checkB.Text        = "Use SUM histogram";
            checkB.Tag         = "Use SUM histogram:\nCalculates histograms for all images\nand merge them into one";
            checkB.Width       = 150;
            checkB.Checked     = true;
            checkB.MouseHover += Control_MouseOver;
            checkB.Location    = new Point(7, 35);
            optionGB.Controls.Add(checkB);
            checkB.BringToFront();
            checkB.CheckedChanged += new EventHandler(delegate(object o, EventArgs e)
            {
                TifFileInfo fi = IA.TabPages.TabCollections[IA.TabPages.SelectedIndex].tifFI;
                fi.sumHistogramChecked[fi.cValue] = checkB.Checked;
                if (((CheckBox)o).Focused == true)
                {
                    IA.ReloadImages();
                }
            });
            {
                Button btn = ProcessBtn;
                btn.Width     = 115;
                btn.FlatStyle = FlatStyle.Standard;
                btn.BackColor = SystemColors.ButtonFace;
                btn.ForeColor = Color.Black;
                btn.Text      = "Process";
                btn.Location  = new Point(5, 58);
                optionGB.Controls.Add(btn);
                btn.BringToFront();
                btn.Click += new EventHandler(delegate(object o, EventArgs a)
                {
                    int MLEVEL = thresholdsNumCB.SelectedIndex + 1;

                    if (IA.Segmentation.SegmentationCBox.SelectedIndex == 2)
                    {
                        IA.Segmentation.Kmeans.Start(MLEVEL);
                        return;
                    }

                    if (IA.Segmentation.SegmentationCBox.SelectedIndex != 1)
                    {
                        return;
                    }

                    TifFileInfo fi = IA.TabPages.TabCollections[IA.TabPages.SelectedIndex].tifFI;
                    if (fi.available == false)
                    {
                        MessageBox.Show("Image is not ready yet! \nTry again later.");
                    }
                    else
                    {
                        //background worker
                        var bgw = new BackgroundWorker();
                        bgw.WorkerReportsProgress = true;
                        bgw.DoWork += new DoWorkEventHandler(delegate(Object o1, DoWorkEventArgs a1)
                        {
                            try
                            {
                                //Segmentation event
                                run(fi, MLEVEL);
                            }
                            catch { }
                            //report progress
                            ((BackgroundWorker)o1).ReportProgress(0);
                        });

                        bgw.ProgressChanged += new ProgressChangedEventHandler(delegate(Object o1, ProgressChangedEventArgs a1)
                        {
                            fi.available = true;
                            IA.FileBrowser.StatusLabel.Text = "Ready";
                            IA.MarkAsNotSaved();
                            IA.ReloadImages();
                        });
                        //Apply status
                        IA.FileBrowser.StatusLabel.Text = "Segmentation...";
                        fi.available = false;
                        //start bgw
                        bgw.RunWorkerAsync();
                    }
                });
            }
            #endregion Options

            #region Thresholds
            GroupBox threshGB = new GroupBox();
            threshGB.Text      = "Thresholds:";
            threshGB.BackColor = IA.FileBrowser.BackGround2Color1;
            threshGB.ForeColor = IA.FileBrowser.ShriftColor1;
            threshGB.Dock      = DockStyle.Fill;
            threshGB.Height    = 50;
            panel.Controls.Add(threshGB);
            threshGB.BringToFront();

            //Color btns
            Panel colorPanel = new Panel();
            colorPanel.Dock  = DockStyle.Left;
            colorPanel.Width = 25;
            threshGB.Controls.Add(colorPanel);

            Panel UpPanel = new Panel();
            UpPanel.Dock   = DockStyle.Top;
            UpPanel.Height = 15;
            threshGB.Controls.Add(UpPanel);
            UpPanel.BringToFront();

            for (int i = 0; i < colorBtns.Length; i++)
            {
                Button btn = new Button();
                btn.FlatStyle = FlatStyle.Flat;
                btn.FlatAppearance.BorderSize = 0;
                btn.ForeColor = Color.Black;
                btn.Text      = "";
                btn.Tag       = i;
                btn.Dock      = DockStyle.Top;
                btn.Height    = 25;
                colorPanel.Controls.Add(btn);
                colorBtns[i] = btn;
                btn.BringToFront();
                btn.Visible     = false;
                btn.MouseDown  += new MouseEventHandler(ColorBtn_Click);
                btn.MouseHover += new EventHandler(delegate(object o, EventArgs a)
                {
                    if (btn.Text == "")
                    {
                        TurnOnToolTip.SetToolTip(btn, "Color " + ((int)btn.Tag).ToString()
                                                 + ":\nLeft click to Disable\nRight click to change color");
                    }
                    else
                    {
                        TurnOnToolTip.SetToolTip(btn, "Color " + ((int)btn.Tag).ToString()
                                                 + " - Disabled\nLeft click to Enable");
                    }
                });
            }
            //threshold track bars
            for (int i = 0; i < threshTrackBars.Length; i++)
            {
                CTTrackBar tb = new CTTrackBar();
                tb.Initialize();
                tb.Panel.Dock = DockStyle.Top;
                tb.BackColor(IA.FileBrowser.BackGround2Color1);
                tb.ForeColor(IA.FileBrowser.ShriftColor1);
                tb.Panel.Visible = false;
                tb.Refresh(0, 0, 10);
                tb.Name.Text       = "T" + (i + 1).ToString();
                tb.NamePanel.Width = 30;
                threshGB.Controls.Add(tb.Panel);
                threshTrackBars[i] = tb;
                tb.Panel.BringToFront();
                tb.Value.Changed += new ChangedValueEventHandler(delegate(Object o, ChangeValueEventArgs a)
                {
                    TrackBar_ValueChange(a, tb);
                });
            }
            #endregion Thresholds
        }
Example #24
0
        private int xmin;                   //of selection created

        #endregion CellTool variables

        /** Constructs a Wand object from an ImageProcessor. */
        public Wand(ImageAnalyser IA)
        {
            this.IA = IA;
        }