/////////////////////////////////////////////////////////////////////// // Acquire Completed Handler /////////////////////////////////////////////////////////////////////// void experiment_ExperimentCompleted(object sender, ExperimentCompletedEventArgs e) { ((IExperiment)sender).ExperimentCompleted -= acquireCompletedEventHandler_; IFileManager fileManager = LightFieldApplication.FileManager; if (fileManager != null) { // 2.) Find the image ---------------------------------------------------------- //------------------------------------------------------------------------------ // Get the recently acquired file list IList <string> files = fileManager.GetRecentlyAcquiredFileNames(); if (files.Count != 0) { double[] waveLengths; double[] errors; // 3.) Get the xml out of the image and from that pull the calibration/error--- //----------------------------------------------------------------------------- // Get the image dataset IImageDataSet dataSet = fileManager.OpenFile(files[0], System.IO.FileAccess.Read); GetCalibrationAndError(dataSet, out waveLengths, out errors); // 4.) Create a new file of user data //------------------------------------------------------------------------------ ' CreateCalibratedFile(waveLengths, errors); } } }
/////////////////////////////////////////////////////////////////////// // Make a linear ramp of data and display it. /////////////////////////////////////////////////////////////////////// private void GenerateRamps() { // Make A Frame 200x400 pixels ushort[] frame1 = new ushort[200 * 400]; for (int pix = 0; pix < 200 * 400; pix++) { frame1[pix] = (ushort)(pix % 400); } // Make A Frame 300x500 pixels with a 1k bias ushort[] frame2 = new ushort[300 * 500]; for (int pix = 0; pix < 300 * 500; pix++) { frame2[pix] = (ushort)((pix % 500) + 1000); } // Get the addin file manager var datamgr = LightFieldApplication.DataManager; if (datamgr != null) { RegionOfInterest roi = new RegionOfInterest(0, 0, 400, 200, 1, 1); RegionOfInterest roi2 = new RegionOfInterest(0, 0, 500, 300, 1, 1); // Simple Single Region IImageDataSet imageData = datamgr.CreateImageDataSet(frame1, roi, ImageDataFormat.MonochromeUnsigned16); RegionOfInterest[] rois = { roi, roi2 }; List <Array> buffers = new List <Array>(); buffers.Add(frame1); buffers.Add(frame2); // Complex Set Containing Two Regions IImageDataSet imageDataSets = datamgr.CreateImageDataSet(buffers, rois, ImageDataFormat.MonochromeUnsigned16); IDisplay display = LightFieldApplication.DisplayManager; if (display != null) { // Select Data File Compare Mode & 3 Vertical Windows display.ShowDisplay(DisplayLocation.ExperimentWorkspace, DisplayLayout.TwoHorizontal); IDisplayViewer view = null; // Modify the underlying data a little bit before displaying it. ModifyDataExample(imageData, 0); // Put the simple data in window 0 view = display.GetDisplay(DisplayLocation.ExperimentWorkspace, 0); view.Display("SimpleRamp", imageData); // Modify the underlying data a little bit before displaying it. ModifyDataExample(imageDataSets, 1); // Put the complex data in window 1 view = display.GetDisplay(DisplayLocation.ExperimentWorkspace, 1); view.Display("ComplexRamp", imageDataSets); } } }
/////////////////////////////////////////////////////////////////////// private void CreateCalibratedFile(double [] calibration, double [] errors) { // No Calibration So Make Something up if (calibration == null) { calibration = new double[720]; for (int i = 0; i < 720; i++) { calibration[i] = i * 3.0; } } // Size of data passed in ushort[] cosine = new ushort[calibration.Length]; // Generate Curves (Amplitude 100) for (int pix = 0; pix < calibration.Length; pix++) { // Convert To Angle double angle = Math.PI * ((double)pix - 360) / 180.0; // Compute Points cosine[pix] = (ushort)((double)100 * (Math.Cos(angle) + (double)1)); } // Mkae a region of interest (Single Strip) RegionOfInterest roi = new RegionOfInterest(0, 0, calibration.Length, 1, 1, 1); // Get the file manager var filemgr = LightFieldApplication.FileManager; if (filemgr != null) { RegionOfInterest[] rois = { roi }; string root = (string)LightFieldApplication.Experiment.GetValue(ExperimentSettings.FileNameGenerationDirectory); IImageDataSet calSampleData = filemgr.CreateFile(root + "\\CalibrationSample.Spe", rois, 1, ImageDataFormat.MonochromeUnsigned16); // Put Data to frame 1 IImageData data1 = calSampleData.GetFrame(0, 0); data1.SetData(cosine); // Update The XML for the new document SetCalibrationAndError(calSampleData, calibration, errors); // Close the file filemgr.CloseFile(calSampleData); } }
/////////////////////////////////////////////////////////////////////// // Show 4 Plots of Cos vs Sine in Quad Display // 1.) Generates Raw Data // 2.) Builds IImageData(s) with the raw data from the DataManager. // 3.) Gets 4 Displays and Puts 2 Waveforms in each display. /////////////////////////////////////////////////////////////////////// private void PlotSinAndCos() { // Make two curves (720 = 2*PI so its a full cycle) ushort[] cosine = new ushort[720]; ushort[] sine = new ushort[720]; // Generate Curves (Amplitude 100) for (int pix = 0; pix < 720; pix++) { // Convert To Angle double angle = Math.PI * ((double)pix - 360) / 180.0; // Compute Points cosine[pix] = (ushort)((double)100 * (Math.Cos(angle) + (double)1)); sine[pix] = (ushort)((double)100 * (Math.Sin(angle) + (double)1)); } // Get the data manager var datamgr = LightFieldApplication.DataManager; if (datamgr != null) { RegionOfInterest roi = new RegionOfInterest(0, 0, 720, 1, 1, 1); // Create Blobs IImageDataSet cosData = datamgr.CreateImageDataSet(cosine, roi, ImageDataFormat.MonochromeUnsigned16); IImageDataSet sineData = datamgr.CreateImageDataSet(sine, roi, ImageDataFormat.MonochromeUnsigned16); // Get The Display Object IDisplay display = LightFieldApplication.DisplayManager; if (display != null) { // Select Data File Compare Mode & 4 Even Windows display.ShowDisplay(DisplayLocation.ExperimentWorkspace, DisplayLayout.FourEven); IDisplayViewer view = null; // Put the data in all 4 windows for (int i = 0; i <= 3; i++) { view = display.GetDisplay(DisplayLocation.ExperimentWorkspace, i); view.Display("Cosine", cosData); IDisplaySource sinSource = display.Create("Sine", sineData); view.Add(sinSource); } } } }
/////////////////////////////////////////////////////////////////////// // Acquire Completed Handler /////////////////////////////////////////////////////////////////////// void experiment_ExperimentCompleted(object sender, ExperimentCompletedEventArgs e) { ((IExperiment)sender).ExperimentCompleted -= acquireCompletedEventHandler_; IFileManager fileManager = app_.FileManager; if (fileManager != null) { // Get the recently acquired file list IList <string> files = fileManager.GetRecentlyAcquiredFileNames(); // Open the last one if there is one if (files.Count != 0) { // We can't update our observable collection here it must be done on this dispatcher not // from within this callback Dispatcher.Invoke( System.Windows.Threading.DispatcherPriority.Background, new Action(delegate() { // Get the image dataset IImageDataSet dataSet = fileManager.OpenFile(files[0], System.IO.FileAccess.Read); // show the origin origin.Text = dataSet.TimeStampOrigin.ToString(); // Display the Meta Data for each frame for (int i = 0; i < dataSet.Frames; i++) { Metadata md = dataSet.GetFrameMetaData(i); // by adding the meta data to the observable collection it appears in the listview stampCollection_.Add(new StampData { ExposureStart = md.ExposureStarted, ExposureEnd = md.ExposureEnded, Frame = md.FrameTrackingNumber, GateTrackingDelay = md.GateTrackingDelay, GateTrackingWidth = md.GateTrackingWidth, TrackingPhase = md.ModulationTrackingPhase }); } })); } } }
/////////////////////////////////////////////////////////////////////// // Synchronous Full Frame Acquire /////////////////////////////////////////////////////////////////////// private void AcquireFullFrameSync(object sender, RoutedEventArgs e) { // Are we in a state we can do this? if (!ValidateAcquisition()) { return; } // Get the experiment object IExperiment experiment = application_.Experiment; // Full Frame experiment.SetFullSensorRegion(); int images = 3; int frames = 1; experiment.SetValue(ExperimentSettings.AcquisitionFramesToStore, frames); for (int i = 1; i <= images; i++) { // Capture 1 Frame IImageDataSet set = experiment.Capture(frames); // Stop processing if we do not have all frames if (set.Frames != frames) { // Clean up the image data set set.Dispose(); throw new ArgumentException("Frames are not equal"); } // Get the data from the current frame Array imageData = set.GetFrame(0, frames - 1).GetData(); // Cache the frame IImageData imageFrame = set.GetFrame(0, frames - 1); PrintData(imageData, imageFrame, i, images); } }
/////////////////////////////////////////////////////////////////////// // The first index of the filemanager's GetRecentlyAcquireFileNames is // always the last file acquired.. /////////////////////////////////////////////////////////////////////// void ShowImageDataFromLastAcquire() { // Expected resulting file name string resultName = (string)experiment_.GetValue(ExperimentSettings.AcquisitionOutputFilesResult); // Open the last acquired file IList <string> files = fileManager_.GetRecentlyAcquiredFileNames(); // Is our result in the acquired if (files.Contains(resultName)) { // Open file IImageDataSet dataSet = fileManager_.OpenFile(resultName, FileAccess.Read); // Stop processing if we do not have all frames if (dataSet.Frames != frames_) { // Close the file fileManager_.CloseFile(dataSet); throw new ArgumentException("Frames are not equal"); } // Cache image data Array imageData = dataSet.GetFrame(0, frames_ - 1).GetData(); // Cache the frame IImageData imageFrame = dataSet.GetFrame(0, frames_ - 1); // Print some of the cached data PrintData(imageData, imageFrame); // Close the file fileManager_.CloseFile(dataSet); } }
/////////////////////////////////////////////////////////////////////// // Change some of the values in the underlying IImageDataSet /////////////////////////////////////////////////////////////////////// void ModifyDataExample(IImageDataSet imageData, int roiIdx) { // Demostrate how to access the data and change it var rois = imageData.Regions; // Get the width & the height int h = rois[roiIdx].Height; int w = rois[roiIdx].Width; // Get sub image arrays from the data set IImageData row = imageData.GetRow(roiIdx, 0, h / 2); IImageData col = imageData.GetColumn(roiIdx, 0, w / 2); IImageData pix = imageData.GetPixel(roiIdx, 0, h / 2, w / 2); // Create new arrays to replace data ushort[] rowData = new ushort[w]; ushort[] colData = new ushort[h]; ushort[] pixData = new ushort[1]; // Build up new data with values for (int x = 0; x < w; x++) { rowData[x] = (ushort)(5000 + x); } for (int y = 0; y < h; y++) { colData[y] = (ushort)(10000 + y); } // bright pixel pixData[0] = 65535; // Push back to original buffer row.SetData(rowData); col.SetData(colData); pix.SetData(pixData); }
void ShowFrame(string fileName) { var filemgr = application_.FileManager; if (filemgr != null) { IImageDataSet dataSet = filemgr.OpenFile(fileName, FileAccess.Read); IImageData d = dataSet.GetFrame(0, 0); // Convert IImageData To Bitmap System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(d.Width, d.Height); ushort[] data = new ushort[bmp.Width * bmp.Height]; // convert them all to the smallest (simple example for now) var pixels = bmp.Width * bmp.Height; switch (d.Format) { case ImageDataFormat.MonochromeFloating32: { float[] ptr = (float[])d.GetData(); for (int k = 0; k < pixels; k++) { data[k] = (ushort)ptr[k]; } } break; case ImageDataFormat.MonochromeUnsigned16: { ushort[] ptr = (ushort[])d.GetData(); for (int k = 0; k < pixels; k++) { data[k] = (ushort)ptr[k]; } } break; case ImageDataFormat.MonochromeUnsigned32: { uint[] ptr = (uint[])d.GetData(); for (int k = 0; k < pixels; k++) { data[k] = (ushort)ptr[k]; } } break; } short rgb_value = 0; int i = 0; for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { rgb_value = (short)((ushort)data[i] / (ushort)256); bmp.SetPixel(x, y, System.Drawing.Color.FromArgb(rgb_value, rgb_value, rgb_value)); i++; } } // Convert To WPF Bitmap System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); // Set the source image1.Source = bitmapSource; // Show the image in a new display viewer viewer_.DisplayViewer.Display("Sample Display", dataSet); } }
//////////////////////////////////////////////////////////////////////// // The following routine demonstrates how to create files using the // LightField Addin SDK. // // Create 1 File with 2 Frames and 1 Region (TwoFrameOneRoi.Spe) // Create 1 File with 1 Frames and 2 Regions (OneFrameTwoRoi.Spe) //////////////////////////////////////////////////////////////////////// private void GenerateFiles() { // Get the addin file manager var filemgr = LightFieldApplication.FileManager; if (filemgr != null) { /////////////////////////////////////////////////////////////// // Part 1: Two Frames 1 Region /////////////////////////////////////////////////////////////// int[] w1 = { 100 }; int[] h1 = { 200 }; // Pseudo Frame 1 Region 1, Frame 2 Region 1 ushort[] frame1 = new ushort[100 * 200]; ushort[] frame2 = new ushort[100 * 200]; for (int pix = 0; pix < 100 * 200; pix++) { frame1[pix] = (ushort)pix; frame2[pix] = (ushort)(pix * 2); } // Folder Selector var dialog = new System.Windows.Forms.FolderBrowserDialog(); dialog.Description = "Please choose folder for resulting SPE file(s)."; System.Windows.Forms.DialogResult result = dialog.ShowDialog(); // Something bad happened we don't want to write the files. if (result != System.Windows.Forms.DialogResult.OK) { return; } // Local variable containing path string path = dialog.SelectedPath; // Create a file with 2 frames and the proper width and height // The file is initially created as empty and the user must load data to it. RegionOfInterest roi = new RegionOfInterest(0, 0, w1[0], h1[0], 1, 1); RegionOfInterest[] rois = { roi }; IImageDataSet TwoFrameOneRoi = filemgr.CreateFile(path + "\\TwoFrameOneRoi.spe", rois, 2, // Frames ImageDataFormat.MonochromeUnsigned16); // Put Data to frame 1 IImageData data1 = TwoFrameOneRoi.GetFrame(0, 0); data1.SetData(frame1); // Put Data to frame 2 IImageData data2 = TwoFrameOneRoi.GetFrame(0, 1); data2.SetData(frame2); // Finally close this file filemgr.CloseFile(TwoFrameOneRoi); /////////////////////////////////////////////////////////////// // Part 2: 1 Frame 2 Regions /////////////////////////////////////////////////////////////// int[] w2 = { 300, 500 }; int[] h2 = { 400, 600 }; // Pseudo Frame 2 Region 1 ushort[] frame1_roi1 = new ushort[300 * 400]; for (int pix = 0; pix < 300 * 400; pix++) { frame1_roi1[pix] = (ushort)pix; } // Pseudo Frame 2 Region 2 ushort[] frame1_roi2 = new ushort[500 * 600]; for (int pix = 0; pix < 500 * 600; pix++) { frame1_roi2[pix] = (ushort)pix; } // Create a file, get the buffer and fill it in for each region // The file is initially created as empty and the user must load data to it. // The regions can not overlap RegionOfInterest r1 = new RegionOfInterest(0, 0, w2[0], h2[0], 1, 1); RegionOfInterest r2 = new RegionOfInterest(w2[0] + 1, h2[0] + 1, w2[1], h2[1], 1, 1); RegionOfInterest[] rois2 = { r1, r2 }; IImageDataSet OneFrameTwoRoi = filemgr.CreateFile(path + "\\OneFrameTwoRoi.spe", rois2, 1, // Frames ImageDataFormat.MonochromeUnsigned16); // Put Data To Region 1 IImageData data2_roi1 = OneFrameTwoRoi.GetFrame(0, 0); data2_roi1.SetData(frame1_roi1); // Data To Region 2 IImageData data2_roi2 = OneFrameTwoRoi.GetFrame(1, 0); data2_roi2.SetData(frame1_roi2); // Finally close this file filemgr.CloseFile(OneFrameTwoRoi); } }
/////////////////////////////////////////////////////////////////////// public void SetCalibrationAndError(IImageDataSet dataSet, double[] waveLengths, double[] errors) { // Get the text file string xmlText = LightFieldApplication.FileManager.GetXml(dataSet); // Create a new XML Document XmlDocument xDoc = new XmlDocument(); // Convert to proper encoding buffer byte[] byteArray = new byte[xmlText.Length]; var encoding = Encoding.UTF8; byteArray = encoding.GetBytes(xmlText); // Convert to Memory Stream MemoryStream memoryStream = new MemoryStream(byteArray); memoryStream.Seek(0, SeekOrigin.Begin); // Load The XmlDocument xDoc.Load(memoryStream); // Create an XmlNamespaceManager to resolve the default namespace. XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable); nsmgr.AddNamespace("pi", @"http://www.princetoninstruments.com/spe/2009"); // Find Calibrations XmlNode calRoot = xDoc.SelectSingleNode("//pi:Calibrations", nsmgr); if (calRoot != null) { // Get WavelengthMapping XmlNode waveMapping = calRoot.SelectSingleNode("//pi:WavelengthMapping", nsmgr); // Create if it is non existing if (waveMapping == null) { waveMapping = xDoc.CreateNode(XmlNodeType.Element, "WavelengthMapping", @"http://www.princetoninstruments.com/spe/2009"); calRoot.AppendChild(waveMapping); } if (waveMapping != null) { // Set Wavelength Errors (wave0,error0 wave1,error1 wave2,error2 .... //-------------------------------------------------------------------------- if (errors != null) { // Get Wavelength Errors XmlNode waveErrors = waveMapping.SelectSingleNode("//pi:WavelengthError", nsmgr); // Create if it is non existing and needed if (waveErrors == null) { waveErrors = xDoc.CreateNode(XmlNodeType.Element, "WavelengthError", @"http://www.princetoninstruments.com/spe/2009"); waveMapping.AppendChild(waveErrors); } if (waveErrors != null) { string errorString = string.Empty; for (int i = 0; i < errors.Length; i++) { errorString += waveLengths[i].ToString() + ',' + errors[i].ToString(); // Space for next pair if not last one if (i != errors.Length - 1) { errorString += ' '; } } waveErrors.InnerText = errorString; } } //-------------------------------------------------------------------------- else { XmlNode waves = waveMapping.SelectSingleNode("//pi:Wavelength", nsmgr); // Create if it is non existing if (waves == null) { waves = xDoc.CreateNode(XmlNodeType.Element, "Wavelength", @"http://www.princetoninstruments.com/spe/2009"); waveMapping.AppendChild(waves); } if (waves != null) { string waveString = string.Empty; for (int i = 0; i < waveLengths.Length; i++) { waveString += waveLengths[i].ToString(); if (i != waveLengths.Length - 1) { waveString += ','; } } waves.InnerText = waveString; } } } } // Finally Update the document with the new xml LightFieldApplication.FileManager.SetXml(dataSet, xDoc.InnerXml); }
/////////////////////////////////////////////////////////////////////// public void GetCalibrationAndError(IImageDataSet dataSet, out double[] waveLengths, out double[] errors) { // Start off empty errors = null; waveLengths = null; string xmlText = LightFieldApplication.FileManager.GetXml(dataSet); // Create a new XML Document XmlDocument xDoc = new XmlDocument(); // Convert to proper encoding buffer byte[] byteArray = new byte[xmlText.Length]; var encoding = Encoding.UTF8; byteArray = encoding.GetBytes(xmlText); // Convert to Memory Stream MemoryStream memoryStream = new MemoryStream(byteArray); memoryStream.Seek(0, SeekOrigin.Begin); // Load The XmlDocument xDoc.Load(memoryStream); // Create an XmlNamespaceManager to resolve the default namespace. XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable); nsmgr.AddNamespace("pi", @"http://www.princetoninstruments.com/spe/2009"); // Find Calibrations XmlNode calRoot = xDoc.SelectSingleNode("//pi:Calibrations", nsmgr); if (calRoot != null) { // Get WavelengthMapping XmlNode waveMapping = calRoot.SelectSingleNode("//pi:WavelengthMapping", nsmgr); if (waveMapping != null) { // Get Wavelength Errors (wave0,error0 wave1,error1 wave2,error2 .... //-------------------------------------------------------------------------- XmlNode waveErrors = waveMapping.SelectSingleNode("//pi:WavelengthError", nsmgr); if (waveErrors != null) { string[] pairs = waveErrors.InnerText.Split(' '); waveLengths = new double[pairs.Count()]; errors = new double[pairs.Count()]; if ((pairs != null) && (pairs.Count() > 0)) { for (int i = 0; i < pairs.Count(); i++) { string[] temp = pairs[i].Split(','); waveLengths[i] = XmlConvert.ToDouble(temp[0]); errors[i] = XmlConvert.ToDouble(temp[1]); } } } // No Errors //-------------------------------------------------------------------------- else { XmlNode waves = waveMapping.SelectSingleNode("//pi:Wavelength", nsmgr); if (waves != null) { // Readin values into array string[] split = waves.InnerText.Split(','); waveLengths = new double[split.Length]; // Convert to doubles for (int i = 0; i < split.Length; i++) { waveLengths[i] = XmlConvert.ToDouble(split[i]); } } } } } }