public static double[] ReadFrequencies(string file) { Fits f = new Fits(file); ImageHDU h = (ImageHDU)f.ReadHDU(); return((double[])h.Kernel); }
public static Image <Gray, UInt16> ReadFITSFile(String ImagePath) { try { Fits f = new Fits(ImagePath); ImageHDU h = (ImageHDU)f.ReadHDU(); System.Array[] img = (System.Array[])h.Kernel; f.Close(); int Width = img.Count(); int Height = img.GetLength(0); UInt16[][] ImgConverted = new UInt16[Width][]; Image <Gray, UInt16> LastestImageCV = new Image <Gray, UInt16>(Width, Height); Int16 MaxNumber = Int16.MaxValue; for (int i = 0; i < Width; i++) { ImgConverted[i] = new UInt16[Height]; for (int j = 0; j < Height; j++) { int Data = MaxNumber + (Int16)img[i].GetValue(j) + 1; ImgConverted[i][j] = (UInt16)Data; LastestImageCV.Data[i, j, 0] = (UInt16)Data; } } return(LastestImageCV); } catch { return(null); } }
public static double[,,] ReadUVW(string file, int fromBl, int toBl) { var f = new Fits(file); var h = (ImageHDU)f.ReadHDU(); // Double Cube Dimensions: baseline, time, uvw var uvw_raw = (Array[])h.Kernel; var time_samples = uvw_raw[0].Length; var length = toBl - fromBl; var uvw = new double[length, time_samples, 3]; for (long i = fromBl; i < toBl; i++) { Array[] bl = (Array[])uvw_raw[i]; for (int j = 0; j < time_samples; j++) { double[] values = (double[])bl[j]; uvw[i - fromBl, j, 0] = values[0]; //u uvw[i - fromBl, j, 1] = -values[1]; //v uvw[i - fromBl, j, 2] = values[2]; //w } } return(uvw); }
public static Complex[,,] ReadVisibilities(string file, int fromBl, int toBl, int timessamplesCount, int channelsCount, double norm) { var f = new Fits(file); var h = (ImageHDU)f.ReadHDU(); //Double cube Dimensions: baseline, time, channel, pol, complex_component var vis_raw = (Array[])h.Kernel; var length = toBl - fromBl; var visibilities = new Complex[length, timessamplesCount, channelsCount]; for (int i = fromBl; i < toBl; i++) { Array[] bl = (Array[])vis_raw[i]; for (int j = 0; j < timessamplesCount; j++) { Array[] times = (Array[])bl[j]; for (int k = 0; k < channelsCount; k++) { Array[] channel = (Array[])times[k]; double[] pol_XX = (double[])channel[0]; double[] pol_YY = (double[])channel[3]; //add polarizations XX and YY together to form Intensity Visibilities only visibilities[i - fromBl, j, k] = new Complex( (pol_XX[0] + pol_YY[0]) / norm, (pol_XX[1] + pol_YY[1]) / norm); } } } return(visibilities); }
private static void readImage(string fileName, out Int16[][] img, out Header hdr) { Fits f = new Fits(fileName); ImageHDU h = (ImageHDU)f.ReadHDU(); hdr = h.Header; Int32 height = h.Axes[0]; Int32 width = h.Axes[1]; Int16 [][] inImg = new Int16[height][]; int x, y; img = new Int16[height][]; object[] rows = (System.Array[])h.Kernel; for (y = 0; y < height / 2; y++) { inImg[y] = new Int16[2 * width]; for (x = 0; x < width; x++) { inImg[y][x] = (Int16)((Int16[])rows[2 * y])[x]; inImg[y][x + width] = (Int16)((Int16[])rows[2 * y + 1])[x]; } } for (y = 0; y < height; y++) { img[y] = new Int16[width]; for (x = 0; x < width; x++) { img[y][x] = (Int16)((Int16[])rows[y])[x]; } } #if false for (y = 0; y < height; y += 2) { int inX = 0; int inY = y / 2; img[y] = new Int16[width]; img[y + 1] = new Int16[width]; for (x = 0; x < width; x += 2) { img[y][x] = inImg[inY][inX++]; img[y + 1][x] = inImg[inY][inX++]; img[y + 1][x + 1] = inImg[inY][inX++]; img[y][x + 1] = inImg[inY][inX++]; } } #endif }
public static int CountBaselines(string file) { var f = new Fits(file); var h = (ImageHDU)f.ReadHDU(); // Double Cube Dimensions: baseline, time, uvw var uvw_raw = (Array[])h.Kernel; var baselines = uvw_raw.Length; return(baselines); }
private static void xreadImage(string fileName, out Int16[][] img, out Header hdr) { Fits f = new Fits(fileName); ImageHDU h = (ImageHDU)f.ReadHDU(); hdr = h.Header; Int32 height = h.Axes[0]; Int32 width = h.Axes[1]; object[] rows = (System.Array[])h.Kernel; Int16[] inImg = new Int16[height * width]; int x, y; int idx = 0; for (y = 0; y < height; y++) { Int16[] row = (Int16[])rows[y]; for (x = 0; x < width; x++) { inImg[idx++] = row[x]; } } Int16 [] outImg = new Int16[height * width]; int srcIdx, destIdx; for (srcIdx = 0, destIdx = 0, y = 0; y < height / 2; y++) { for (x = 0; x < width / 2; x++) { outImg[destIdx] = inImg[srcIdx++]; outImg[width + destIdx++] = inImg[srcIdx++]; outImg[width + destIdx] = inImg[srcIdx++]; outImg[destIdx++] = inImg[srcIdx++]; } destIdx += width; } img = new Int16[height][]; for (srcIdx = 0, y = 0; y < height; y++) { img[y] = new Int16[width]; for (x = 0; x < width; x++) { img[y][x] = outImg[srcIdx++]; } } }
public static double[,] ReadImageDouble(string file) { Fits f = new Fits(file); ImageHDU h = (ImageHDU)f.ReadHDU(); var imgRaw = (Array[])h.Kernel; var output = new double[imgRaw.Length, imgRaw[0].Length]; for (int i = 0; i < imgRaw.Length; i++) { var row = (double[])imgRaw[i]; for (int j = 0; j < row.Length; j++) { output[i, j] = row[j]; } } return(output); }
public static double[,] ReadBeam(string file) { var f = new Fits(file); var h = (ImageHDU)f.ReadHDU(); var raw = (Array[])h.Kernel; var img = new double[raw.Length, raw.Length]; for (int i = 0; i < raw.Length; i++) { var col = (double[])raw[i]; for (int j = 0; j < col.Length; j++) { img[i, j] = col[j]; } } return(img); }
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 bool[,,] ReadFlags(string file, int fromBl, int toBl, int timessamplesCount, int channelsCount) { var length = toBl - fromBl; var output = new bool[length, timessamplesCount, channelsCount]; var f = new Fits(file); var h = (ImageHDU)f.ReadHDU(); var flags_raw = (Array[])h.Kernel; for (int i = fromBl; i < toBl; i++) { Array[] bl = (Array[])flags_raw[i]; for (int j = 0; j < timessamplesCount; j++) { Array[] times = (Array[])bl[j]; for (int k = 0; k < channelsCount; k++) { double[] pols = (double[])times[k]; var sum = 0.0; for (int l = 0; l < pols.Length; l++) { sum += pols[l]; } //visibilitiy has been flagged if (sum == 0) { output[i - fromBl, j, k] = false; } else { output[i - fromBl, j, k] = true; } } } } return(output); }
/// <summary> /// Corrige el nombre un archivo "fits". /// Dejando intacta la ruta (carpeta) original. /// /// Además si es un archivo fits, corrige el contenido del campo /// object en la misma lógica que la corrección del nombre del archivo. /// /// Primero se corrige el contenido del archivo y luego el nombre. /// </summary> /// <param name="archivo"></param> private void correctFits(FileInfo archivo) { logger.Info("correctFits:archivo=" + archivo.Name); String ruta; String oldFileName; String newFileName; String extension; String oldFullFilename; String newFullFilename; Boolean requiereRename; //True solo si se detecta que es pertinente un rename requiereRename = false; ruta = archivo.DirectoryName; oldFileName = archivo.Name; extension = archivo.Extension; newFileName = archivo.Name; oldFullFilename = archivo.FullName; if (extension == ".fts") { requiereRename = true; logger.Info(";.fts->.fits"); newFileName = newFileName.Replace(".fts", ".fits"); } if (oldFileName.Contains("+")) { requiereRename = true; logger.Info(";'+'->'p'"); newFileName = newFileName.Replace("+", "p"); /////////////// if ((extension == ".fts") || (extension == ".fits")) { Fits fitsFile; String strObject; // El string que hay que corregir. String strCorrectedObject; fitsFile = new Fits(oldFullFilename); BasicHDU hdu; hdu = fitsFile.ReadHDU(); HeaderCard hcOBJECT;// Target object name <---- Asi esta comentado en MaximDL hcOBJECT = hdu.Header.FindCard("OBJECT"); strObject = hcOBJECT.Value; if (strObject.Contains("+")) { strCorrectedObject = strObject.Replace("+", "p"); hcOBJECT.Value = strCorrectedObject; } hdu.Header.Rewrite(); fitsFile.Close(); } /////////////// } if (requiereRename) { newFullFilename = ruta + Path.DirectorySeparatorChar + newFileName; logger.Info(";" + oldFullFilename + "->" + newFullFilename); try { archivo.MoveTo(newFullFilename); } catch (Exception e) { logger.Error(e.Message); } } //Console.WriteLine("#"); }
/// <summary> /// Revisa las coordenadas de un archivo "fits". /// Dejando intacta la ruta (carpeta) original. /// /// Avisa por pantalla: /// - Si las coordenadas del filename no coinciden con las del fits. /// /// </summary> /// <param name="archivo"></param> private void revisaRaDecFits(FileInfo archivo) { //logger.Info("correctFits:archivo=" + archivo.Name); String ruta; String shortFileName; String extension; String fullFilename; ruta = archivo.DirectoryName; shortFileName = archivo.Name; extension = archivo.Extension; fullFilename = archivo.FullName; /////////////// if ((extension == ".fts") || (extension == ".fits")) { Fits fitsFile; String strObject; String strObjectRA; String strObjectDEC; fitsFile = new Fits(fullFilename); BasicHDU hdu; hdu = fitsFile.ReadHDU(); HeaderCard hcOBJECT; // Target object name <---- Asi esta comentado en MaximDL HeaderCard hcOBJCTRA; // [hms J2000] Target right ascension <---- Asi esta comentado en MaximDL HeaderCard hcOBJCTDEC; // [dms +N J2000] Target declination <---- Asi esta comentado en MaximDL hcOBJECT = hdu.Header.FindCard("OBJECT"); //OBJECT = 'F1910178-615834' hcOBJCTRA = hdu.Header.FindCard("OBJCTRA"); //OBJCTRA = '19 10 17.80' hcOBJCTDEC = hdu.Header.FindCard("OBJCTDEC"); //OBJCTDEC = '-61 58 34.0' strObject = hcOBJECT.Value; strObjectRA = null; strObjectDEC = null; if (hcOBJCTRA != null) { strObjectRA = hcOBJCTRA.Value; } if (hcOBJCTDEC != null) { strObjectDEC = hcOBJCTDEC.Value; } fitsFile.Close(); if ((strObjectRA != null) && (strObject.StartsWith("F"))) { StringBuilder radec; //strObjectRA = EntreComillas(strObjectRA)[1]; radec = new StringBuilder(); radec.Append("F"); radec.Append(strObjectRA.Replace(" ", "").Replace(".", "").Substring(0, 7)); //if (!strObjectDEC.StartsWith("-")) //{ // radec.Append("p"); //} radec.Append(strObjectDEC.Replace(" ", "").Replace(".", "").Replace("+", "p").Substring(0, 7)); StringBuilder comparacion; comparacion = new StringBuilder(); comparacion.Append(strObject); comparacion.Append("=="); comparacion.Append(radec); comparacion.Append(" --> "); Boolean match; match = strObject.Equals(radec.ToString()); comparacion.Append(match); Console.WriteLine(comparacion.ToString()); if (!match) { StringBuilder mensaje; mensaje = new StringBuilder(); mensaje.Append(comparacion.ToString()); mensaje.Append("\trm\t"); mensaje.Append(shortFileName); mensaje.Append("\t"); mensaje.Append(fullFilename); Console.WriteLine(mensaje.ToString()); } } } /////////////// }
/// <summary> /// Modifica el header de un archivo .fits, previo al envio /// del archivo a otro servidor. /// </summary> /// <param name="fitsFullPath"></param> /// <returns>True si consigue modificar el header del archivo</returns> public Boolean CompletaFitsHeader(String fitsFullPath) { this.refreshATC02XmlStatus(); if (!this.atc02Status.IsFresh()) { logger.Info("ATC02 sin datos recientes, no se actualizara Archivo fits '" + fitsFullPath + "'"); return(false); } FileInfo archivoFitsNuevo; int test; int testLimit; test = 1; testLimit = 4; archivoFitsNuevo = new FileInfo(fitsFullPath); do { test++; if (archivoFitsNuevo.Exists) { break; } else { logger.Warn(String.Format("Archivo '{0}'no existe, intento {1} de {2}, esperando 1 segundo.", fitsFullPath, test, testLimit)); System.Threading.Thread.Sleep(1000); } } while (test <= testLimit); if (!archivoFitsNuevo.Exists) { logger.Error(String.Format("Archivo '{0}'no existe.", fitsFullPath)); return(false); } Boolean respuesta; respuesta = true; // Solo si ocurre alguna excepcion esta variable sera False DateTime Ahora; Ahora = DateTime.Now; Fits fitsFile; System.Threading.Thread.Sleep(1000); fitsFile = new Fits(fitsFullPath); BasicHDU hdu; hdu = fitsFile.ReadHDU(); HeaderCard hcDATE_OBS; // [ISO 8601] UTC date/time of exposure start HeaderCard hcEXPOSURE; // [sec] Duration of exposure hcDATE_OBS = hdu.Header.FindCard("DATE-OBS"); hcEXPOSURE = hdu.Header.FindCard("EXPOSURE"); DateTime dateObs; dateObs = DateTime.Parse(hcDATE_OBS.Value); //// [ISO 8601] UTC date/time of exposure start Double exposure; // [sec] Duration of exposure exposure = Double.Parse(hcEXPOSURE.Value); TimeSpan vejezFits; // Tiempo Transcurrido entre termino de exposición y el presente vejezFits = Ahora.Subtract(dateObs); double vejezSegundos; vejezSegundos = ((vejezFits.TotalSeconds) - exposure); logger.Info("Vejez archivo FITS=" + vejezSegundos + "[segundos]."); // Si la vejez del archiv Fits es menor a veinte segundos // entonces se modifica el encabezado del fits // con la información del ATC02 if (vejezSegundos < 20) { HeaderCard hcFocStep; HeaderCard hcPriTemp; HeaderCard hcSecTemp; HeaderCard hcAmbTemp; HeaderCard hcSetFan; logger.Info("Actualizando archivo FITS:" + fitsFullPath); hcFocStep = hdu.Header.FindCard("FOCSTEP"); hcPriTemp = hdu.Header.FindCard("PRITEMP"); hcSecTemp = hdu.Header.FindCard("SECTEMP"); hcAmbTemp = hdu.Header.FindCard("AMBTEMP"); hcSetFan = hdu.Header.FindCard("SETFAN"); if (hcFocStep == null) { hcFocStep = new HeaderCard("FOCSTEP"); hdu.Header.AddCard(hcFocStep); } if (hcPriTemp == null) { hcPriTemp = new HeaderCard("PRITEMP"); hdu.Header.AddCard(hcPriTemp); } if (hcSecTemp == null) { hcSecTemp = new HeaderCard("SECTEMP"); hdu.Header.AddCard(hcSecTemp); } if (hcAmbTemp == null) { hcAmbTemp = new HeaderCard("AMBTEMP"); hdu.Header.AddCard(hcAmbTemp); } if (hcSetFan == null) { hcSetFan = new HeaderCard("SETFAN"); hdu.Header.AddCard(hcSetFan); } hcFocStep.Value = ("" + Atc02Xml.BflToFocSetp(this.atc02Status.FocusPosition)); hcPriTemp.Value = ("" + this.atc02Status.PrimaryTemperature); hcSecTemp.Value = ("" + this.atc02Status.SecondaryTemperature); hcAmbTemp.Value = ("" + this.atc02Status.AmbientTemperature); hcSetFan.Value = ("" + this.atc02Status.FanPower); System.Threading.Thread.Sleep(4000); try { hdu.Header.Rewrite(); } catch (Exception) { respuesta = false; logger.Error("Error en: hdu.Header.Rewrite();"); } } fitsFile.Close(); // Permitimos al sistema que guarde los cambios en el archivo fits. System.Threading.Thread.Sleep(1000); return(respuesta); }
private FitsHeader ReadFits(string Filename) { /* double RA; * double DEC; * float[][] imageData; * string LocalDate; * double SiteLong; * double SiteLat; */ FitsHeader fitsheader = new FitsHeader(); try { Fits f = new Fits(Filename); ImageHDU h = (ImageHDU)f.ReadHDU(); //other things we might want: // IMAGETYP= 'LIGHT' // NAXIS1 = 7380 / // NAXIS2 = 4908 // EXPTIME = 6.0 / [s] Exposure duration // DATE-LOC= '2020-10-07T01:28:55.164' / Time of observation (local) // GAIN = 1208 / Sensor gain // XPIXSZ = 4.88 / [um] Pixel X axis size // YPIXSZ = 4.88 / [um] Pixel Y axis size // SITELAT = 47.6077777777778 / [deg] Observation site latitude // SITELONG = -122.335 / [deg] Observation site longitude] fitsheader.ImageType = h.Header.GetStringValue("IMAGETYP"); fitsheader.NAXIS1 = h.Header.GetIntValue("NAXIS1"); fitsheader.NAXIS2 = h.Header.GetIntValue("NAXIS2"); fitsheader.DecDeg = h.Header.GetDoubleValue("DEC"); fitsheader.RaDeg = h.Header.GetDoubleValue("RA") / 15; fitsheader.Exposure = h.Header.GetFloatValue("EXPOSURE"); fitsheader.LocalDate = DateTime.ParseExact(h.Header.GetStringValue("DATE-LOC"), "yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); fitsheader.UTCDate = DateTime.ParseExact(h.Header.GetStringValue("DATE-OBS"), "yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); fitsheader.SiteLat = h.Header.GetDoubleValue("SITELAT"); fitsheader.SiteLong = h.Header.GetDoubleValue("SITELONG"); fitsheader.PixelPitch = h.Header.GetFloatValue("XPIXSZ"); fitsheader.Gain = h.Header.GetIntValue("GAIN"); fitsheader.SensorTempC = h.Header.GetFloatValue("CCD-TEMP"); fitsheader.FocalLength = h.Header.GetFloatValue("FOCALLEN"); fitsheader.Object = h.Header.GetStringValue("OBJECT"); /*RA = h.Header.GetDoubleValue("RA") / 15; * DEC = h.Header.GetDoubleValue("DEC"); * LocalDate = h.Header.GetStringValue("DATE-LOC"); * SiteLat = h.Header.GetDoubleValue("SITELAT"); * SiteLong = h.Header.GetDoubleValue("SITELAT"); * * * //imageData = (float[][])h.Kernel; */ f.Close(); } catch { Console.WriteLine("Error opening fits.."); return(fitsheader); } return(fitsheader); }
public static Task <IImageData> Load(Uri filePath, bool isBayered) { return(Task.Run <IImageData>(() => { Fits f = new Fits(filePath); ImageHDU hdu = (ImageHDU)f.ReadHDU(); Array[] arr = (Array[])hdu.Data.DataArray; var dimensions = hdu.Header.GetIntValue("NAXIS"); if (dimensions > 2) { //Debayered Images are not supported. Take the first dimension instead to get at least a monochrome image arr = (Array[])arr[0]; } var width = hdu.Header.GetIntValue("NAXIS1"); var height = hdu.Header.GetIntValue("NAXIS2"); var bitPix = hdu.Header.GetIntValue("BITPIX"); var converter = GetConverter(bitPix); ushort[] pixels = converter.Convert(arr, width, height); //Translate nom.tam.fits into N.I.N.A. FITSHeader FITSHeader header = new FITSHeader(width, height); var iterator = hdu.Header.GetCursor(); while (iterator.MoveNext()) { HeaderCard card = (HeaderCard)((DictionaryEntry)iterator.Current).Value; if (card.Value != null) { if (card.IsStringValue) { header.Add(card.Key, card.Value, card.Comment); } else { if (card.Value == "T") { header.Add(card.Key, true, card.Comment); } else if (card.Value.Contains(".")) { if (double.TryParse(card.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var value)) { header.Add(card.Key, value, card.Comment); } } else { if (int.TryParse(card.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var value)) { header.Add(card.Key, value, card.Comment); } } } } } var metaData = new ImageMetaData(); try { metaData = header.ExtractMetaData(); } catch (Exception ex) { Logger.Error(ex.Message); } return new Model.ImageData.ImageData(pixels, width, height, 16, isBayered, metaData); })); }
// Read a FITS file public Bitmap ReadFile(string FileName) { Fits f2 = new Fits(FileName); ImageHDU h2 = (ImageHDU)f2.ReadHDU(); Header hdr2 = h2.Header; int BitPixLen = hdr2.GetIntValue("BITPIX"); int PixelWidth = hdr2.GetIntValue("NAXIS1"); int PixelHeight = hdr2.GetIntValue("NAXIS2"); object[] img = (object[])h2.Kernel; uint[][] img1 = new uint[PixelHeight][]; byte[][] img2 = new byte[PixelHeight][]; //for (int i = 0; i < PixelHeight; i++) // img2[i] = new byte[PixelWidth]; if (BitPixLen == 32)//int { //读出来又翻转,注意 uint MaxPixelValue = 0x00000000; uint MinPixelValue = 0xFFFFFFFF; for (int i = 0; i < PixelHeight; i++) { img1[i] = (uint[])img[i]; //img强制赋值给img1 img2[i] = new byte[PixelWidth]; for (int j = 0; j < PixelWidth; j++) //求最值 { if (img1[i][j] > MaxPixelValue) { MaxPixelValue = img1[i][j]; } else if ((img1[i][j] > 0) && (img1[i][j] < MinPixelValue)) { MinPixelValue = img1[i][j]; } } } //转换灰度图系数 double m = (MaxPixelValue - MinPixelValue) * 1.0 / 255; for (int i = 0; i < PixelHeight; i++) { for (int j = 0; j < PixelWidth; j++) { if (img1[i][j] > 0) { double tf = (img1[i][j] - MinPixelValue) * 1.0 / m; if (tf >= 255.0) { img2[i][j] = 255; } else { img2[i][j] = Convert.ToByte(tf); } } } } } //Bitmap bmp = ToGrayBitmap(img2, PixelWidth, PixelHeight); //pictureBox1.Image = bmp; return(ToGrayBitmap(img2, PixelWidth, PixelHeight)); }