internal void SaveFitsFrame(string fileName, int width, int height, uint[] framePixels, DateTime timeStamp, float exposureSeconds) { Fits f = new Fits(); object data = SaveImageData(width, height, framePixels); BasicHDU imageHDU = Fits.MakeHDU(data); nom.tam.fits.Header hdr = imageHDU.Header; hdr.AddValue("SIMPLE", "T", null); hdr.AddValue("BITPIX", 32, null); hdr.AddValue("NAXIS", 2, null); hdr.AddValue("NAXIS1", width, null); hdr.AddValue("NAXIS2", height, null); hdr.AddValue("NOTES", m_Note, null); hdr.AddValue("EXPOSURE", exposureSeconds.ToString("0.000", CultureInfo.InvariantCulture), "Exposure, seconds"); hdr.AddValue("DATE-OBS", timeStamp.ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture), m_DateObsComment); hdr.AddValue("TANGRAVE", string.Format("{0} v{1}", VersionHelper.AssemblyProduct, VersionHelper.AssemblyFileVersion), "Tangra version"); hdr.AddValue("END", null, null); f.AddHDU(imageHDU); // Write a FITS file. using (BufferedFile bf = new BufferedFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite)) { f.Write(bf); bf.Flush(); } }
static void writeImage(string fileName, Int16[][] img, Header header) { Fits f = new Fits(); BufferedDataStream s = new BufferedDataStream(new FileStream(fileName, FileMode.Create)); //BufferedFile s = new BufferedFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite); BasicHDU h = FitsFactory.HDUFactory(img); Header hdr = h.Header; f.AddHDU(h); f.Write(s); }
public void saveImageToFitsForSolveOnly(string path, imageInfo image, Array imgArray) { var imageData = (Array)ArrayFuncs.Flatten(imgArray); const double bZero = 0; const double bScale = 1.0; if (image.MaxADU <= 65535) { //bZero = 32768; //imageData = (ushort[])ArrayFuncs.ConvertArray(imageData, typeof(ushort)); } int[] dims = ArrayFuncs.GetDimensions(imgArray); // put the image data in a basic HDU of the fits BasicHDU imageHdu = FitsFactory.HDUFactory(ArrayFuncs.Curl(imageData, dims)); // Add the other fits fields to the HDU imageHdu.AddValue("BZERO", bZero, ""); imageHdu.AddValue("BSCALE", bScale, ""); imageHdu.AddValue("DATAMIN", 0.0, ""); // should this reflect the actual data values imageHdu.AddValue("DATAMAX", image.MaxADU, "pixel values above this level are considered saturated."); imageHdu.AddValue("DATE-OBS", image.LastExposureStartTime, ""); imageHdu.AddValue("XPIXSZ", image.PixelSizeX * image.BinX, "physical X dimension of the sensor's pixels in microns"); // (present only if the information is provided by the camera driver). Includes binning. imageHdu.AddValue("YPIXSZ", image.PixelSizeY * image.BinY, "physical Y dimension of the sensor's pixels in microns"); // (present only if the information is provided by the camera driver). Includes binning. imageHdu.AddValue("XBINNING", image.BinX, ""); imageHdu.AddValue("YBINNING", image.BinY, ""); imageHdu.AddValue("OBJCTRA", image.RA, "Approximate Right Ascension of image centre"); imageHdu.AddValue("OBJCTDEC", image.Dec, "Approximate Declination of image centre"); // save it var fitsImage = new Fits(); fitsImage.AddHDU(imageHdu); //Adds the actual image data (the header info already exists in imageHDU) FileStream fs = null; try { fs = new FileStream(path, FileMode.Create); using (var bds = new BufferedDataStream(fs)) { fs = null; fitsImage.Write(bds); } } finally { if (fs != null) { fs.Dispose(); } } }
public static ImageHDU GetImageHDU(Fits fits) { int i = 0; for (BasicHDU hdu = fits.getHDU(i); hdu != null; ++i) { if (hdu is ImageHDU) { return((ImageHDU)hdu); } } return(null); }
internal static void SaveDarkOrFlatFrame(string fileName, int width, int height, string notes, float[,] averagedData, float exposureSeconds, int numFrames) { Fits f = new Fits(); object data = SaveImageData(width, height, averagedData); BasicHDU imageHDU = Fits.MakeHDU(data); nom.tam.fits.Header hdr = imageHDU.Header; hdr.AddValue("SIMPLE", "T", null); hdr.AddValue("BITPIX", -32 /* Floating Point Data*/, null); hdr.AddValue("NAXIS", 2, null); hdr.AddValue("NAXIS1", width, null); hdr.AddValue("NAXIS2", height, null); if (notes.Length > HeaderCard.MAX_VALUE_LENGTH) { notes = notes.Substring(0, HeaderCard.MAX_VALUE_LENGTH); } hdr.AddValue("NOTES", notes, null); if (exposureSeconds > 0) { hdr.AddValue("EXPOSURE", exposureSeconds.ToString("0.000", CultureInfo.InvariantCulture), null); hdr.AddValue("EXPTIME", exposureSeconds.ToString("0.000", CultureInfo.InvariantCulture), null); } hdr.AddValue("SNAPSHOT", numFrames.ToString(), null); hdr.AddValue("TANGRAVE", string.Format("{0} v{1}", VersionHelper.AssemblyProduct, VersionHelper.AssemblyFileVersion), null); if (TangraConfig.Settings.Generic.ReverseGammaCorrection) { hdr.AddValue("TANGAMMA", TangraConfig.Settings.Photometry.EncodingGamma.ToString("0.0000", CultureInfo.InvariantCulture), null); } if (TangraConfig.Settings.Generic.ReverseCameraResponse) { hdr.AddValue("TANCMRSP", ((int)TangraConfig.Settings.Photometry.KnownCameraResponse).ToString(CultureInfo.InvariantCulture), null); } f.AddHDU(imageHDU); // Write a FITS file. using (BufferedFile bf = new BufferedFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite)) { f.Write(bf); bf.Flush(); } }
public static int GetBZero(BasicHDU imageHDU) { int bzero = 0; HeaderCard bZeroCard = imageHDU.Header.FindCard("BZERO"); if (bZeroCard != null && !string.IsNullOrWhiteSpace(bZeroCard.Value)) { try { bzero = (int)double.Parse(bZeroCard.Value.Replace(',', '.'), CultureInfo.InvariantCulture); } catch { } } return(bzero); }
// Make FITS file public void MakeFile(string FileName, float[][] ImgArray) { //Create a FITS file from an image: Fits f = new Fits(); //BasicHDU h = FitsFactory.HDUFactory(ImgArray); BasicHDU h = Fits.MakeHDU(ImgArray); Header hdr = h.Header; //添加关键字 hdr.AddValue("OBS2", "hss", "Observer"); f.AddHDU(h); BufferedDataStream bf = new BufferedDataStream(new FileStream(FileName, FileMode.Create)); f.Write(bf); bf.Flush(); bf.Close(); }
public frmDefineFitsCube3D(BasicHDU imageHDU, string filesHash, VideoController videoController) : this() { m_VideoController = videoController; m_ImageHDU = imageHDU; m_FilesHash = filesHash; var hasher = new SHA1CryptoServiceProvider(); hasher.Initialize(); var orderedCardNames = new List <string>(); var cursor = m_ImageHDU.Header.GetCursor(); while (cursor.MoveNext()) { var card = m_ImageHDU.Header.FindCard((string)cursor.Key); if (card != null) { m_AllCards.Add(new HeaderEntry(card)); } orderedCardNames.Add((string)cursor.Key); } orderedCardNames.Sort(); byte[] combinedCardNamesBytes = Encoding.UTF8.GetBytes(string.Join("|", orderedCardNames)); var hash = hasher.ComputeHash(combinedCardNamesBytes, 0, combinedCardNamesBytes.Length); m_CardNamesHash = Convert.ToBase64String(hash); cbxNaxisOrder.SelectedIndex = 0; cbxExposure.Items.AddRange(m_AllCards.ToArray()); cbxExposureUnits.Items.Clear(); cbxExposureUnits.Items.AddRange(Enum.GetNames(typeof(TangraConfig.ExposureUnit))); cbxExposureUnits.SelectedIndex = 0; m_TimeStampHelper = new FitsTimestampHelper(m_FilesHash, m_AllCards, UseRecentFitsConfig); ucTimestampControl.Initialise(m_AllCards, m_FilesHash, m_CardNamesHash, m_TimeStampHelper); m_TimeStampHelper.TryIdentifyPreviousConfigApplyingForCurrentFiles(); }
private static bool LoadFitsFileInternal <TData>( string fileName, IFITSTimeStampReader timeStampReader, out TData[,] pixels, out TData medianValue, out Type pixelDataType, out float frameExposure, out bool hasNegativePixels, out short minRawValue, out uint maxVal, CheckOpenedFitsFileCallback callback, LoadFitsDataCallback <TData> loadDataCallback) { Fits fitsFile = new Fits(); using (BufferedFile bf = new BufferedFile(fileName, FileAccess.Read, FileShare.ReadWrite)) { fitsFile.Read(bf); BasicHDU imageHDU = fitsFile.GetHDU(0); Array pixelsArray = (Array)imageHDU.Data.DataArray; return(LoadFitsDataInternal <TData>( imageHDU, pixelsArray, fileName, timeStampReader, out pixels, out medianValue, out pixelDataType, out frameExposure, out hasNegativePixels, out minRawValue, out maxVal, callback, loadDataCallback)); } }
internal void SaveFitsFrame(string fileName, Header header, int width, int height, object data) { Fits f = new Fits(); BasicHDU imageHDU = Fits.MakeHDU(data); nom.tam.fits.Header hdr = imageHDU.Header; hdr.AddValue("SIMPLE", "T", null); hdr.AddValue("BZERO", 0, null); hdr.AddValue("BSCALE", 1, null); hdr.AddValue("NAXIS", 2, null); hdr.AddValue("NAXIS1", width, null); hdr.AddValue("NAXIS2", height, null); string[] RESERVED_KEYS = new string[] { "SIMPLE", "NAXIS", "NAXIS1", "NAXIS2", "BZERO", "BSCALE", "END" }; var cursor = header.GetCursor(); while (cursor.MoveNext()) { HeaderCard card = header.FindCard((string)cursor.Key); if (card != null && !string.IsNullOrWhiteSpace(card.Key) && !RESERVED_KEYS.Contains(card.Key)) { hdr.AddValue(card.Key, card.Value, card.Comment); } } hdr.AddValue("NOTES", m_Note, null); hdr.AddValue("TANGRAVE", string.Format("{0} v{1}", VersionHelper.AssemblyProduct, VersionHelper.AssemblyFileVersion), "Tangra version"); hdr.AddValue("END", null, null); f.AddHDU(imageHDU); // Write a FITS file. using (BufferedFile bf = new BufferedFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite)) { f.Write(bf); bf.Flush(); } }
private BasicHDU ReadFIT(string fileName) { Fits f = new Fits(fileName); try { BasicHDU hdus = f.ReadHDU(); if (hdus != null) { hdus.Info(); // TEST: NUM SHARP TEST ImageHDU imgHdu = (ImageHDU)f.GetHDU(0); numSharp.InitImage(imgHdu, fileName); } return(hdus); } catch (Exception e) { throw e; } }
public static void Save(string strFile) { float[][] x = new float[30][]; for (int i = 0; i < x.Length; i++) { x[i] = new float[30]; for (int j = 0; j < x[i].Length; j++) { x[i][j] = 3; } } bool t = typeof(Array).Equals(x.GetType()); Fits f = new Fits(); Header hdr = new Header(); hdr.Bitpix = 8; hdr.Simple = true; hdr.Naxes = 2; hdr.AddValue("NAXIS1", 30, ""); hdr.AddValue("NAXIS2", 30, ""); FitsFactory.UseAsciiTables = false; Data d = FitsFactory.DataFactory(hdr); BasicHDU h = FitsFactory.HDUFactory(x); f.addHDU(h); FileStream os = new FileStream(strFile, FileMode.Create); f.Write(os); }
public static FitsType GetFitsType(string fileName) { Fits fitsFile = new Fits(); using (BufferedFile bf = new BufferedFile(fileName, FileAccess.Read, FileShare.ReadWrite)) { fitsFile.Read(bf); BasicHDU imageHDU = fitsFile.GetHDU(0); if (fitsFile.NumberOfHDUs == 1 && imageHDU.Axes.Length == 3 && imageHDU.Axes[0] == 3) { return(FitsType.RGBFrames); } if (fitsFile.NumberOfHDUs == 1 && imageHDU.Axes.Length == 2) { return(FitsType.SingleFrame); } } return(FitsType.Invalid); }
public void WriteFrameImpl(IntPtr intPtr, int p, RawFrameInfo info) { object data = MarshalToCLR(intPtr, p); Fits fits = new Fits(); BasicHDU hdu = FitsFactory.HDUFactory(data); if ((data is short[][] || data is short[][][]) && _significantBitDepth > 8) { hdu.AddValue("BZERO", 32768.0, ""); } AddMetadataToFrame(info, hdu); fits.AddHDU(hdu); using (FileStream fs = File.Create(Path.GetTempFileName())) { using (BufferedDataStream f = new BufferedDataStream(fs)) { fits.Write(f); } } }
public static FitsCubeType GetFitsCubeType(string fileName) { Fits fitsFile = new Fits(); using (BufferedFile bf = new BufferedFile(fileName, FileAccess.Read, FileShare.ReadWrite)) { fitsFile.Read(bf); BasicHDU imageHDU = fitsFile.GetHDU(0); if (fitsFile.NumberOfHDUs == 1 && imageHDU.Axes.Length == 3) { return(FitsCubeType.ThreeAxisCube); } if (fitsFile.NumberOfHDUs > 1 && imageHDU.Axes.Length == 2) { return(FitsCubeType.MultipleHDUsCube); } } return(FitsCubeType.NotACube); }
public static bool LoadFitsDataInternal <TData>( BasicHDU imageHDU, Array pixelsArray, string fileName, IFITSTimeStampReader timeStampReader, out TData[,] pixels, out TData medianValue, out Type pixelDataType, out float frameExposure, out bool hasNegativePixels, out short minRawValue, out uint maxVal, CheckOpenedFitsFileCallback callback, LoadFitsDataCallback <TData> loadDataCallback) { hasNegativePixels = false; if (callback != null && !(callback(imageHDU))) { pixels = new TData[0, 0]; medianValue = default(TData); pixelDataType = typeof(TData); frameExposure = 0; minRawValue = 0; maxVal = 0; return(false); } int bzero = GetBZero(imageHDU); bool isMidPoint; double?fitsExposure = null; try { ParseExposure(fileName, imageHDU.Header, timeStampReader, out isMidPoint, out fitsExposure); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } frameExposure = fitsExposure.HasValue ? (float)fitsExposure.Value : 0; loadDataCallback(pixelsArray, imageHDU.Axes[0], imageHDU.Axes[1], bzero, out pixels, out medianValue, out pixelDataType, out hasNegativePixels, out minRawValue, out maxVal); return(true); }
internal void ProcessFitsFrame(string fileName, BasicHDU fitsImage) { object data = null; if (m_UsesROI) { Array dataArray = (Array)fitsImage.Data.DataArray; object entry = dataArray.GetValue(0); if (entry is byte[]) { data = GetFitsDataRegion <byte>(dataArray); } else if (entry is short[]) { data = GetFitsDataRegion <short>(dataArray); } else if (entry is int[]) { data = GetFitsDataRegion <int>(dataArray); } else if (entry is float[]) { data = GetFitsDataRegion <float>(dataArray); } else if (entry is double[]) { data = GetFitsDataRegion <double>(dataArray); } } else { data = fitsImage.Data.DataArray; } SaveFitsFrame(fileName, fitsImage.Header, m_RegionOfInterest.Width, m_RegionOfInterest.Height, data); }
private void BuildCalSpecDb() { var db = new CalSpecDatabase(); int totalBad = 0; string[] lines2 = File.ReadAllLines(@"F:\WORK\tangra3\Tangra 3\VideoOperations\Spectroscopy\AbsFluxCalibration\Standards\AbsFlux-TangraStars.csv"); for (int i = 1; i < lines2.Length; i++) { string[] tokens = lines2[i].Split(','); string calSpecId = tokens[0].Trim(); string RA_FK5_Hours = tokens[1].Trim(); string DEG_FK5_Deg = tokens[2].Trim(); string pmRA = tokens[3].Trim(); string pmDec = tokens[4].Trim(); string specType = tokens[5].Trim(); string magV = tokens[6].Trim(); string magBV = tokens[7].Trim(); string absFluxId = tokens[8].Trim(); string stisFlag = tokens[9].Trim(); string fitsFilePath = tokens[10].Trim(); int stisFrom = int.Parse(tokens[11].Trim()); int stisTo = int.Parse(tokens[12].Trim()); string tyc2 = tokens[13].Trim(); string ucac4 = tokens[14].Trim(); if (!string.IsNullOrEmpty(pmRA) && !string.IsNullOrEmpty(pmDec)) { var star = new CalSpecStar() { CalSpecStarId = calSpecId, AbsFluxStarId = absFluxId, STIS_Flag = stisFlag, FITS_File = fitsFilePath, TYC2 = tyc2, U4 = ucac4, pmRA = double.Parse(pmRA), pmDE = double.Parse(pmDec), MagV = double.Parse(magV), MagBV = double.Parse(magBV), SpecType = specType, RA_J2000_Hours = AstroConvert.ToRightAcsension(RA_FK5_Hours), DE_J2000_Deg = AstroConvert.ToDeclination(DEG_FK5_Deg) }; string filePath = Path.GetFullPath(@"Z:\CALSPEC\current_calspec\" + fitsFilePath); using (var bf = new BufferedFile(filePath, FileAccess.Read, FileShare.ReadWrite)) { var fitsFile = new Fits(); fitsFile.Read(bf); BasicHDU imageHDU = fitsFile.GetHDU(1); var table = (ColumnTable)imageHDU.Data.DataArray; double[] wavelengths = (double[])table.Columns[0]; float[] fluxes = (float[])table.Columns[1]; short[] goodnessFlags = (short[])table.Columns[5]; for (int j = 0; j < fluxes.Length; j++) { if (wavelengths[j] < stisFrom) { continue; } if (wavelengths[j] > stisTo) { break; } if (goodnessFlags[j] != 0) { star.DataPoints.Add(wavelengths[j], fluxes[j]); } else { totalBad++; } } fitsFile.Close(); } db.Stars.Add(star); } } using (var compressedStream = new FileStream(@"F:\WORK\tangra3\Tangra 3\VideoOperations\Spectroscopy\AbsFluxCalibration\Standards\CalSpec.db", FileMode.CreateNew, FileAccess.Write)) using (var deflateStream = new DeflateStream(compressedStream, CompressionMode.Compress, true)) { using (var writer = new BinaryWriter(deflateStream)) { db.Serialize(writer); } } using (var compressedStream = new FileStream(@"F:\WORK\tangra3\Tangra 3\VideoOperations\Spectroscopy\AbsFluxCalibration\Standards\CalSpec.db", FileMode.Open, FileAccess.Read)) using (var deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true)) { using (var reader = new BinaryReader(deflateStream)) { var db2 = new CalSpecDatabase(reader); Trace.WriteLine(db2.Stars.Count); } } MessageBox.Show(totalBad.ToString() + " bad entries excluded."); string[] fitsFiles = Directory.GetFiles(@"Z:\CALSPEC\current_calspec", "*.fit"); var dist = new Dictionary <int, int>(); foreach (string filePath in fitsFiles) { using (var bf = new BufferedFile(filePath, FileAccess.Read, FileShare.ReadWrite)) { var fitsFile = new Fits(); fitsFile.Read(bf); var bld = new StringBuilder(); BasicHDU headerHDU = fitsFile.GetHDU(0); BasicHDU imageHDU = fitsFile.GetHDU(1); for (int i = 0; i < headerHDU.Header.NumberOfCards; i++) { string cardString = headerHDU.Header.GetCard(i); bld.AppendFormat("# {0}\r\n", cardString); } for (int i = 0; i < imageHDU.Header.NumberOfCards; i++) { string cardString = imageHDU.Header.GetCard(i); bld.AppendFormat("# {0}\r\n", cardString); } var table = (ColumnTable)imageHDU.Data.DataArray; if (table.Columns.Length == 7 && table.Columns[0] is double[] && table.Columns[1] is float[] && table.Columns[2] is float[] && table.Columns[3] is float[] && table.Columns[4] is float[] && table.Columns[5] is short[] && table.Columns[6] is float[]) { double[] wavelengths = (double[])table.Columns[0]; float[] fluxes = (float[])table.Columns[1]; float[] col2 = (float[])table.Columns[2]; float[] col3 = (float[])table.Columns[3]; float[] col4 = (float[])table.Columns[4]; short[] goodnessFlags = (short[])table.Columns[5]; float[] exposures = (float[])table.Columns[6]; for (int i = 0; i < fluxes.Length; i++) { if (wavelengths[i] < 2000) { continue; } if (wavelengths[i] > 15000) { break; } bld.Append(wavelengths[i].ToString().PadLeft(20)); bld.Append(fluxes[i].ToString().PadLeft(20)); bld.Append(col2[i].ToString().PadLeft(20)); bld.Append(col3[i].ToString().PadLeft(20)); bld.Append(col4[i].ToString().PadLeft(20)); bld.Append(goodnessFlags[i].ToString().PadLeft(15)); bld.Append(exposures[i].ToString().PadLeft(15)); bld.AppendLine(); int expMS = (int)Math.Round(exposures[i] * 1000); if (!dist.ContainsKey(expMS)) { dist.Add(expMS, 0); } dist[expMS]++; } } string outFileName = Path.ChangeExtension(filePath, ".txt"); File.WriteAllText(outFileName, bld.ToString()); fitsFile.Close(); } } var output = new StringBuilder(); foreach (int key in dist.Keys) { output.AppendFormat("{0}s = {1}\r\n", (key / 1000.0).ToString("0.0"), dist[key]); } MessageBox.Show(output.ToString()); }
private void BuildAbsFlux() { var indexFile = new StringBuilder(); indexFile.AppendLine("BD and HD CALSPEC stars with STIS fluxes between 3000 and 10000 Angstroms"); indexFile.AppendLine("Name FK5_Coordinates_J2000 Type Mag B-V File_Name"); foreach (CalSpecStar star in CalSpecDatabase.Instance.Stars) { if (star.AbsFluxStarId.StartsWith("TYC")) { continue; } string modifiedId = star.AbsFluxStarId.Replace(" ", "_"); if (modifiedId.Length < 10) { modifiedId += "_"; } while (modifiedId.Length < 10) { int firstUnderScorePos = modifiedId.IndexOf("_"); modifiedId = modifiedId.Substring(0, firstUnderScorePos) + "_" + modifiedId.Substring(firstUnderScorePos); } string raStr = AstroConvert.ToStringValue(star.RA_J2000_Hours, "HH MM SS.TTT"); string deStr = AstroConvert.ToStringValue(star.DE_J2000_Deg, "+DD MM SS.TT"); string dataFileName = Path.GetFileNameWithoutExtension(star.FITS_File) + "_t1.txt"; string line = string.Format("{0}{1} {2} {3}{4} {5} {6}\r\n", modifiedId.PadRight(14), raStr, deStr, star.SpecType.PadRight(7), star.MagV.ToString("0.00").PadLeft(5), star.MagBV.ToString("0.00").PadLeft(5), dataFileName); indexFile.Append(line); string filePath = Path.GetFullPath(@"Z:\CALSPEC\current_calspec\" + star.FITS_File); double wavelengthFrom = star.DataPoints.Keys.Min(); double wavelengthTo = star.DataPoints.Keys.Max(); using (var bf = new BufferedFile(filePath, FileAccess.Read, FileShare.ReadWrite)) { var fitsFile = new Fits(); fitsFile.Read(bf); BasicHDU imageHDU = fitsFile.GetHDU(1); var table = (ColumnTable)imageHDU.Data.DataArray; double[] wavelengths = (double[])table.Columns[0]; float[] fluxes = (float[])table.Columns[1]; float[] col2 = (float[])table.Columns[2]; float[] col3 = (float[])table.Columns[3]; float[] col4 = (float[])table.Columns[4]; short[] goodnessFlags = (short[])table.Columns[5]; float[] exposures = (float[])table.Columns[6]; var dataFile = new StringBuilder(); dataFile.AppendLine(" WAVELENGTH FLUX STATERROR SYSERROR FWHM DATAQUAL TOTEXP"); dataFile.AppendLine(" 1D 1E 1E 1E 1E 1I 1E"); dataFile.AppendLine(" ANGSTROMS FLAM FLAM FLAM ANGSTROMS NONE SEC"); for (int j = 0; j < fluxes.Length; j++) { if (wavelengths[j] < wavelengthFrom) { continue; } if (wavelengths[j] > wavelengthTo) { break; } string dataLine = string.Format("{0}{1}{2}{3}{4} {5}{6}", ((int)Math.Round(wavelengths[j])).ToString().PadLeft(16), fluxes[j].ToString("E4").PadLeft(14), col2[j].ToString("E4").PadLeft(14), col3[j].ToString("E4").PadLeft(14), col4[j].ToString("#.0").PadLeft(13), goodnessFlags[j].ToString(), exposures[j].ToString("E1").PadLeft(12)); dataFile.AppendLine(dataLine); } fitsFile.Close(); File.WriteAllText(@"Z:\AbsFlux\v3\" + dataFileName, dataFile.ToString()); } } File.WriteAllText(@"Z:\AbsFlux\v3\AbsFluxCALSPECstars.txt", indexFile.ToString()); }
private void CreateDirectoryAndSortImages(string dstPath, string targetName, string[] files, string[] filesFullPath, string dateFolder) { HashSet <string> fileTypesHashSet = new HashSet <string>(); //destToImages = dstPath + "\\" + targetName + "\\" + dateFolder + "\\"; // Create Light Frames directories //if (application_DropDown.Text == "Astro Photography Tools") //{ HashSet <string> objectNames = new HashSet <string>(); for (int i = 0; i < filesFullPath.Length; i++) { string fileTypeTemp; // Get the header of each file var headerInfo = ReadFIT(filesFullPath[i]).Header; var imageType = headerInfo.FindCard("IMAGETYP").Value; string filterType = ""; if (!date_DateTaken.SelectedDate.HasValue) { var tempDate = System.IO.File.GetLastWriteTime(filesFullPath[i]); //var tempDate = DateTime.Parse(headerInfo.FindCard("DATE-OBS").Value); dateFolder = tempDate.ToString("yyyMMdd"); // TODO: temp dont store second date if (!dateToStore.ContainsValue(dateFolder) && !dateToStore.ContainsKey(headerInfo.FindCard("OBJECT").Value)) { // Same value with different date in the same folder causes this to be an error dateToStore.Add(headerInfo.FindCard("OBJECT").Value, dateFolder); } } switch (imageType) { case "Light Frame": if (string.IsNullOrWhiteSpace(txtbx_objectName.Text)) { targetName = headerInfo.FindCard("OBJECT").Value; if (string.IsNullOrEmpty(targetName)) { targetName = "NOTARGET"; } } break; default: targetName = "NOTARGET"; //destToImages = dstPath + "\\" + targetName + "\\" + dateFolder + "\\"; break; } if (!destToImages.ContainsKey(headerInfo.FindCard("OBJECT").Value)) { destToImages.Add(headerInfo.FindCard("OBJECT").Value, dstPath + "\\" + targetName + "\\" + dateFolder + "\\"); } var cureDirToCreate = dstPath + "\\" + targetName + "\\" + dateFolder + "\\"; if (imageType == "Light Frame" || imageType == "Flat Frame") { filterType = headerInfo.FindCard("FILTER").Value; } if (!fileTypesHashSet.Contains(imageType + "/" + filterType)) { // If the file type is not already in the hash set then add it fileTypesHashSet.Add(imageType + "/" + filterType); if (filterType == "") { System.IO.Directory.CreateDirectory(cureDirToCreate + imageType + "s"); } else { System.IO.Directory.CreateDirectory(cureDirToCreate + imageType + "s\\" + filterType); } } switch (imageType) { case "Light Frame": fileTypeTemp = "\\Light Frames\\" + headerInfo.FindCard("FILTER").Value + "\\"; break; case "Dark Frame": fileTypeTemp = "\\Dark Frames\\"; break; case "Flat Frame": fileTypeTemp = "\\Flat Frames\\" + filterType + "\\"; break; default: fileTypeTemp = "\\UNKNOWN\\"; break; } System.IO.File.Copy(filesFullPath[i], txtbx_dstfolder.Text + "\\" + targetName + "\\" + dateFolder + "\\" + fileTypeTemp + files[i]); // Get the FITS image data information BasicHDU hdu = ReadFIT(filesFullPath[i]); if (string.IsNullOrWhiteSpace(txtbx_objectName.Text)) { // No object name if (imageType == "Light Frame" && !objectNames.Contains(hdu.Header.FindCard("OBJECT").Value)) { hduToGetInfoFrom.Add(hdu); objectNames.Add(hdu.Header.FindCard("OBJECT").Value); } } else { if (imageType == "Light Frame" && !objectNames.Contains(txtbx_objectName.Text)) { hduToGetInfoFrom.Add(hdu); objectNames.Add(txtbx_objectName.Text); } } lblStatus.Text = hdu.Instrument; } //} }
public void saveImageToFits(string path, clsSharedData sd) { var imageData = (Array)ArrayFuncs.Flatten(sd.imgArray); const double bZero = 0; const double bScale = 1.0; if (sd.theImage.MaxADU <= 65535) { //bZero = 32768; //imageData = (ushort[])ArrayFuncs.ConvertArray(imageData, typeof(ushort)); } int[] dims = ArrayFuncs.GetDimensions(sd.imgArray); //Array image = ArrayFuncs.Curl(imageData, dims); // put the image data in a basic HDU of the fits BasicHDU imageHdu = FitsFactory.HDUFactory(ArrayFuncs.Curl(imageData, dims)); // put the other data in the HDU imageHdu.AddValue("BZERO", bZero, ""); imageHdu.AddValue("BSCALE", bScale, ""); imageHdu.AddValue("DATAMIN", 0.0, ""); // should this reflect the actual data values imageHdu.AddValue("DATAMAX", sd.theImage.MaxADU, "pixel values above this level are considered saturated."); imageHdu.AddValue("INSTRUME", sd.theImage.Description, ""); imageHdu.AddValue("EXPTIME", sd.theImage.LastExposureDuration, "duration of exposure in seconds."); imageHdu.AddValue("DATE-OBS", sd.theImage.LastExposureStartTime, ""); imageHdu.AddValue("XPIXSZ", sd.theImage.PixelSizeX * sd.theImage.BinX, "physical X dimension of the sensor's pixels in microns"); // (present only if the information is provided by the camera driver). Includes binning. imageHdu.AddValue("YPIXSZ", sd.theImage.PixelSizeY * sd.theImage.BinY, "physical Y dimension of the sensor's pixels in microns"); // (present only if the information is provided by the camera driver). Includes binning. imageHdu.AddValue("XBINNING", sd.theImage.BinX, ""); imageHdu.AddValue("YBINNING", sd.theImage.BinY, ""); imageHdu.AddValue("XORGSUBF", sd.theImage.StartX, "subframe origin on X axis in binned pixels"); imageHdu.AddValue("YORGSUBF", sd.theImage.StartY, "subframe origin on Y axis in binned pixels"); imageHdu.AddValue("CBLACK", (double)sd.theImage.Min, ""); imageHdu.AddValue("CWHITE", (double)sd.theImage.Max, ""); imageHdu.AddValue("SWCREATE", "Nite Ops", "string indicating the software used to create the file"); imageHdu.AddValue("OBJCTRA", sd.theImage.RA, "Approximate Right Ascension of image centre"); imageHdu.AddValue("OBJCTDEC", sd.theImage.Dec, "Approximate Declination of image centre"); imageHdu.AddValue("OBJCTALT", sd.theImage.Alt, "Approximate Altitude of image centre"); imageHdu.AddValue("OBJCTAZ", sd.theImage.Az, "Approximate Azimuth of image centre"); // extensions as specified by SBIG try { imageHdu.AddValue("CCD_TEMP", sd.theImage.CCDTemperature, "sensor temperature in degrees C"); // TODO sate this at the start of exposure . Absent if temperature is not available. } catch (Exception) { imageHdu.Info(); } if (sd.theImage.CanSetCCDTemperature) { imageHdu.AddValue("SET-TEMP", sd.theImage.SetCCDTemperature, "CCD temperature setpoint in degrees C"); } if (sd.theImage.objectName != "") { imageHdu.AddValue("OBJECT", sd.theImage.objectName, "The name of the object"); } else { imageHdu.AddValue("OBJECT", "Unknown", "The name of the object"); } imageHdu.AddValue("TELESCOP", Properties.Settings.Default.imaging_telescope, "Telescope used to acquire this image"); // user-entered information about the telescope used. imageHdu.AddValue("OBSERVER", Properties.Settings.Default.your_name, "Name of the observer"); // user-entered information; the observer’s name. //DARKTIME – dark current integration time, if recorded. May be longer than exposure time. imageHdu.AddValue("IMAGETYP", sd.theImage.frameType + " Frame", "Type of image"); //ISOSPEED – ISO camera setting, if camera uses ISO speeds. //JD_GEO – records the geocentric Julian Day of the start of exposure. //JD_HELIO – records the Heliocentric Julian Date at the exposure midpoint. //NOTES – user-entered information; free-form notes. //READOUTM – records the selected Readout Mode (if any) for the camera. //imageHdu.AddValue("SBSTDVER", "SBFITSEXT Version 1.0", "version of the SBIG FITS extensions supported"); // save it var fitsImage = new Fits(); fitsImage.AddHDU(imageHdu); //Adds the actual image data (the header info already exists in imageHDU) FileStream fs = null; try { fs = new FileStream(path, FileMode.Create); using (var bds = new BufferedDataStream(fs)) { fs = null; fitsImage.Write(bds); } } finally { if (fs != null) { fs.Dispose(); } } }
internal static Pixelmap BuildFitsPixelmap(int width, int height, uint[] pixelsFlat, int bitPix, bool hasUtcTimeStamps, double?exposure, DateTime?timestamp, BasicHDU fitsImage, Dictionary <string, string> cards) { byte[] displayBitmapBytes = new byte[width * height]; byte[] rawBitmapBytes = new byte[(width * height * 3) + 40 + 14 + 1]; TangraCore.PreProcessors.EnsurePixelRange(pixelsFlat, width, height, bitPix, 0); uint[] flatPixelsCopy = new uint[pixelsFlat.Length]; Array.Copy(pixelsFlat, flatPixelsCopy, pixelsFlat.Length); TangraCore.PreProcessors.ApplyPreProcessingPixelsOnly(pixelsFlat, flatPixelsCopy, width, height, bitPix, 0 /* No normal value for FITS files */, exposure.HasValue ? (float)exposure.Value : 0); TangraCore.GetBitmapPixels(width, height, flatPixelsCopy, rawBitmapBytes, displayBitmapBytes, true, (ushort)bitPix, 0); Bitmap displayBitmap = Pixelmap.ConstructBitmapFromBitmapPixels(displayBitmapBytes, width, height); Pixelmap rv = new Pixelmap(width, height, bitPix, flatPixelsCopy, displayBitmap, displayBitmapBytes); rv.UnprocessedPixels = pixelsFlat; if (hasUtcTimeStamps) { rv.FrameState.CentralExposureTime = timestamp.HasValue ? timestamp.Value : DateTime.MinValue; rv.FrameState.ExposureInMilliseconds = exposure.HasValue ? (float)(exposure.Value * 1000.0) : 0; } rv.FrameState.Tag = fitsImage; rv.FrameState.AdditionalProperties = new SafeDictionary <string, object>(); foreach (string key in cards.Keys) { rv.FrameState.AdditionalProperties.Add(key, cards[key]); } return(rv); }
private ThreeAxisFITSCubeFrameStream( string fileName, Fits fitsFile, BufferedFile bufferedFile, BasicHDU imageHDU, FITSTimeStampReader timeStampReader, int widthIndex, int heightIndex, int frameIndex, short minPixelValue, uint maxPixelValue, int bitPix, int negPixCorrection) { m_FileName = fileName; bool isMidPoint; double?exposureSecs; var startExposure = timeStampReader.ParseExposure(null, imageHDU.Header, out isMidPoint, out exposureSecs); if (startExposure.HasValue && exposureSecs.HasValue) { m_ExposureSeconds = exposureSecs.Value; m_FirstFrameMidTime = startExposure.Value; } m_MinPixelValue = minPixelValue; m_MaxPixelValue = maxPixelValue; m_Bpp = bitPix; m_FitsFile = fitsFile; m_TimeStampReader = timeStampReader; m_BufferedFile = bufferedFile; m_ImageHDU = imageHDU; m_HeightIndex = heightIndex; m_WidthIndex = widthIndex; m_FrameIndex = frameIndex; m_NumFrames = m_ImageHDU.Axes[frameIndex]; m_Height = m_ImageHDU.Axes[heightIndex]; m_Width = m_ImageHDU.Axes[widthIndex]; m_ArrayData = (Array)m_ImageHDU.Data.DataArray; m_BZero = FITSHelper2.GetBZero(m_ImageHDU); m_NegPixCorrection = negPixCorrection; m_Cards = new Dictionary <string, string>(); var cursor = m_ImageHDU.Header.GetCursor(); while (cursor.MoveNext()) { HeaderCard card = m_ImageHDU.Header.FindCard((string)cursor.Key); if (card != null && !string.IsNullOrWhiteSpace(card.Key) && card.Key != "END") { if (m_Cards.ContainsKey(card.Key)) { m_Cards[card.Key] += "\r\n" + card.Value; } else { m_Cards.Add(card.Key, card.Value); } } } HasUTCTimeStamps = startExposure.HasValue; VideoFileType = string.Format("FITS.{0}::Cube3D", bitPix); }
internal void SaveFitsFrame(int frameNo, string fileName, int width, int height, uint[] framePixels, DateTime timeStamp, float exposureSeconds) { Fits f = new Fits(); object data = m_ExportAs8BitFloat ? (object)SaveNormalizedFloatImageData(width, height, framePixels) : (object)SaveImageData(width, height, framePixels); BasicHDU imageHDU = Fits.MakeHDU(data); nom.tam.fits.Header hdr = imageHDU.Header; hdr.AddValue("SIMPLE", "T", null); hdr.AddValue("BITPIX", m_ExportAs8BitFloat ? -32 : 32, null); hdr.AddValue("BZERO", 0, null); hdr.AddValue("BSCALE", 1, null); hdr.AddValue("NAXIS", 2, null); hdr.AddValue("NAXIS1", width, null); hdr.AddValue("NAXIS2", height, null); hdr.AddValue("EXPOSURE", exposureSeconds.ToString("0.000", CultureInfo.InvariantCulture), "Exposure, seconds"); hdr.AddValue("DATE-OBS", timeStamp.ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture), m_DateObsComment); hdr.AddValue("CAMERA", m_VideoCamera, "Video camera model (observer specified)"); hdr.AddValue("FILENAME", m_VideoController.FileName, null); hdr.AddValue("FRAMENO", frameNo, null); if (m_VideoFormat == VideoFileFormat.AAV || m_VideoFormat == VideoFileFormat.AAV2) { hdr.AddValue("NOTES", "No instrumental delay has been applied to DATE-OBS.", null); if (m_ExportAs8BitFloat) { hdr.AddValue("VIDEOFMT", m_NativeFormat, "Native analogue video format"); if (m_IntegrationRate > 0) { hdr.AddValue("INTGRRTE", m_IntegrationRate.ToString(), "Integration rate in video frames"); } } } else { hdr.AddValue("NOTES", string.Format("Converted from {0} file.", m_VideoFormat), null); } foreach (var kvp in m_AdditionalFileHeaders) { hdr.AddValue(kvp.Key, kvp.Value.Item1, kvp.Value.Item2); } hdr.AddValue("TANGRAVE", string.Format("{0} v{1}", VersionHelper.AssemblyProduct, VersionHelper.AssemblyFileVersion), "Tangra version"); hdr.AddValue("END", null, null); f.AddHDU(imageHDU); // Write a FITS file. using (BufferedFile bf = new BufferedFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite)) { f.Write(bf); bf.Flush(); } }
private void AddMetadataToFrame(RawFrameInfo info, BasicHDU hdu) { if (info == null) { info = new RawFrameInfo() { ColourSpace = _colourSpaceId } } ; if (info.ExposureMs.HasValue) { hdu.AddValue("EXPTIME", info.ExposureMs.Value / 1000, ""); } if (info.PixelSize.HasValue) { hdu.AddValue("XPIXSZ", info.PixelSize.Value, ""); hdu.AddValue("YPIXSZ", info.PixelSize.Value, ""); } if (info.Binning > 0) { hdu.AddValue("XBINNING", info.Binning, ""); hdu.AddValue("YBINNING", info.Binning, ""); } if (info.SensorTemp.HasValue) { hdu.AddValue("CCD-TEMP", info.SensorTemp.Value, ""); } switch (info.ColourSpace) { case ColourSpaceId.Mono: break; case ColourSpaceId.RGB: hdu.AddValue("COLORTYP", "RGB", ""); break; case ColourSpaceId.Bayer_RGGB: hdu.AddValue("COLORTYP", "RGGB", ""); break; case ColourSpaceId.Bayer_GRBG: hdu.AddValue("COLORTYP", "GRBG", ""); break; case ColourSpaceId.Bayer_GBRG: hdu.AddValue("COLORTYP", "GBRG", ""); break; case ColourSpaceId.Bayer_BGGR: hdu.AddValue("COLORTYP", "BGGR", ""); break; case ColourSpaceId.Bayer_CYYM: hdu.AddValue("COLORTYP", "CYYM", ""); break; case ColourSpaceId.Bayer_YMCY: hdu.AddValue("COLORTYP", "YMCY", ""); break; case ColourSpaceId.Bayer_MYYC: hdu.AddValue("COLORTYP", "MYYC", ""); break; case ColourSpaceId.Bayer_Unknown: break; } hdu.AddValue("SWCREATE", "SharpCap", ""); hdu.AddValue("DATE-OBS", DateTime.UtcNow.ToString("s"), ""); if (!string.IsNullOrEmpty(info.CameraName)) { hdu.AddValue("INSTRUME", info.CameraName, ""); } }