예제 #1
0
        private HeaderKeyValue ConvertType(HeaderCard card)
        {
            if (!card.KeyValuePair)
            {
                return(new HeaderKeyValue(card.Key, null, card.Comment));
            }

            // We know it isn't a string, so it's either a boolean or a number.
            // Boolean is expected to be "T" or "F". In all other cases it's a number.
            if (card.Value == "T" || card.Value == "F")
            {
                return(new HeaderKeyValue(card.Key, card.Value == "T", card.Comment));
            }

            double val       = 0;
            var    converted = double.TryParse(card.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out val);

            if (converted)
            {
                return(new HeaderKeyValue(card.Key, val, card.Comment));
            }

            // Fallback is the header value as string.
            return(new HeaderKeyValue(card.Key, card.Value, card.Comment));
        }
예제 #2
0
        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);
        }
예제 #3
0
        /// <summary>
        /// Считывание заголовка HDU-блока
        /// </summary>
        /// <param name="file">имя файла</param>
        /// <param name="index">порядковый номер HDU-блока</param>
        /// <param name="table">список параметров из заголовка HDU-блока</param>
        /// <param name="hasImage">наличие изображения после заголовка</param>
        /// <returns></returns>
        public bool ReadHeader(string file, int index, out List <string[]> table, out bool hasImage)
        {
            fits = new Fits(file, FileAccess.Read);
            hdus = fits.Read();
            if (hdus == null)
            {
                table    = null;
                hasImage = false;
            }
            // Построчное считывание и сохранение параметров из заголовка: ключевое слово-значение-комментарий
            // сохранение в список table
            table = new List <string[]> {
            };
            var hdr = hdus[index].Header;

            for (int j = 0; j < hdr.NumberOfCards; j++)
            {
                var hc = new HeaderCard(hdr.GetCard(j));
                var sa = new string[3] {
                    hc.Key, hc.Value, hc.Comment
                };
                table.Add(sa);
            }

            // Кол-во осей в data unit
            int naxis = 0;

            if (hdr.ContainsKey("SIMPLE"))
            {
                // Для первого HDU
                if (hdr.ContainsKey("NAXIS"))
                {
                    naxis = hdr.GetIntValue("NAXIS");
                }
            }
            else if (hdr.ContainsKey("XTENSION"))
            {
                // Для остальных HDU-расширений
                if (hdr.ContainsKey("ZNAXIS"))
                {
                    naxis = hdr.GetIntValue("ZNAXIS");
                }
            }
            hasImage = (naxis == 2);
            return(table.Count != 0);
        }
예제 #4
0
        public bool ReadHeader(string file, int index, out List <string[]> table, out bool hasImage)
        {
            fits = new Fits(file, FileAccess.Read);
            hdus = fits.Read();

            if (hdus == null)
            {
                table = null; hasImage = false; return(false);
            }

            table = new List <string[]> {
            };
            var hdr = hdus[index].Header;

            for (int j = 0; j < hdr.NumberOfCards; j++)
            {
                var hc = new HeaderCard(hdr.GetCard(j));
                var sa = new string[3] {
                    hc.Key, hc.Value, hc.Comment
                };
                table.Add(sa);
            }

            int naxis = 0;

            if (hdr.ContainsKey("SIMPLE"))
            {
                // Простой HDU
                if (hdr.ContainsKey("NAXIS"))
                {
                    naxis = hdr.GetIntValue("NAXIS");
                }
            }
            else if (hdr.ContainsKey("XTENSION"))
            {
                // HDU-расширение
                if (hdr.ContainsKey("ZNAXIS"))
                {
                    naxis = hdr.GetIntValue("ZNAXIS");
                }
            }
            hasImage = (naxis == 2);
            return(table.Count != 0);
        }
예제 #5
0
        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();
            }
        }
예제 #6
0
        private void ParseFirstFrame(out uint[] pixelsFlat, out short minPixelValue, out uint maxPixelValue, out int bpp, out int bzero, out bool hasNegativePixels)
        {
            int      width;
            int      height;
            DateTime?timestamp;
            double?  exposure;
            int      bz    = 0;
            var      cards = new Dictionary <string, string>();

            FITSHelper.Load16BitFitsFile(null, Load16BitFitsFile, null,
                                         (hdu) =>
            {
                var cursor = hdu.Header.GetCursor();
                bz         = FITSHelper.GetBZero(hdu);
                while (cursor.MoveNext())
                {
                    HeaderCard card = hdu.Header.FindCard((string)cursor.Key);
                    if (card != null && !string.IsNullOrWhiteSpace(card.Key) && card.Key != "END")
                    {
                        if (cards.ContainsKey(card.Key))
                        {
                            cards[card.Key] += "\r\n" + card.Value;
                        }
                        else
                        {
                            cards.Add(card.Key, card.Value);
                        }
                    }
                }
            }, out pixelsFlat, out width, out height, out bpp, out timestamp, out exposure, out minPixelValue, out maxPixelValue, out hasNegativePixels);

            bzero         = bz;
            MinPixelValue = minPixelValue;
            BZero         = bz;

            FITSHelper.Load16BitFitsFile(null, Load16BitFitsFileWithNegativePixels, null, null, out pixelsFlat, out width, out height, out bpp, out timestamp, out exposure, out minPixelValue, out maxPixelValue, out hasNegativePixels);
        }
예제 #7
0
파일: Form1.cs 프로젝트: ozkomer/rts2syntax
        /// <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);
        }
예제 #8
0
        private static DateTime?ParseExposureInternal(Header header, out bool isMidPoint, out double?fitsExposure)
        {
            // FITS Card definitions taken from here:
            // http://www.cyanogen.com/help/maximdl/FITS_File_Header_Definitions.htm
            // http://www.cv.nrao.edu/fits/documents/standards/year2000.txt

            isMidPoint   = false;
            fitsExposure = null;

            HeaderCard exposureCard = header.FindCard("EXPOSURE");

            if (exposureCard == null)
            {
                exposureCard = header.FindCard("EXPTIME");
            }
            if (exposureCard == null)
            {
                exposureCard = header.FindCard("RAWTIME");
            }
            if (exposureCard != null && !string.IsNullOrWhiteSpace(exposureCard.Value))
            {
                double doubleNum;
                if (double.TryParse(exposureCard.Value.Trim().Replace(',', '.'), NumberStyles.Number, CultureInfo.InvariantCulture, out doubleNum))
                {
                    fitsExposure = doubleNum;
                }
                else
                {
                    throw new FormatException(string.Format("Cannot parse FITS exposure '{0}' as a floating point number.", exposureCard.Value));
                }
            }


            string     dateTimeStr = null;
            HeaderCard timeCard    = header.FindCard("TIMEOBS");
            HeaderCard dateCard;

            if (timeCard != null)
            {
                dateCard = header.FindCard("DATEOBS");
                if (dateCard != null)
                {
                    dateTimeStr = string.Format("{0}T{1}", dateCard.Value, timeCard.Value);
                }
            }
            else
            {
                dateCard = header.FindCard("DATE-OBS");
                timeCard = header.FindCard("TIME-OBS");
                if (timeCard != null && dateCard != null)
                {
                    dateTimeStr = string.Format("{0}T{1}", dateCard.Value, timeCard.Value);
                }
                else if (dateCard != null)
                {
                    dateTimeStr = dateCard.Value;
                }
                else
                {
                    timeCard = header.FindCard("MIDPOINT");
                    if (timeCard != null)
                    {
                        dateTimeStr = timeCard.Value;
                        isMidPoint  = true;
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(dateTimeStr))
            {
                Match regexMatch = FITS_DATE_REGEX.Match(dateTimeStr);
                if (regexMatch.Success)
                {
                    DateTime startObs = DateTime.Parse(regexMatch.Groups["DateStr"].Value.Trim(), CultureInfo.InvariantCulture);
                    // DATE-OBS is the start of the observation, unless given in "MIDPOINT"
                    if (!isMidPoint && fitsExposure.HasValue)
                    {
                        return(startObs.AddSeconds(fitsExposure.Value / 2.0));
                    }
                    else
                    {
                        return(startObs);
                    }
                }
            }

            return(null);
        }
예제 #9
0
        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);
        }
예제 #10
0
파일: FITS.cs 프로젝트: daleghent/NINA
        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);
            }));
        }
예제 #11
0
        private bool LoadDarkFlatOrBiasFrameInternal(string title, ref float[,] pixels, ref float medianValue, ref float exposureSeconds, ref int imagesCombined)
        {
            string filter = "FITS Image 16 bit (*.fit;*.fits)|*.fit;*.fits";

            string fileName;

            if (m_VideoController.ShowOpenFileDialog(title, filter, out fileName) == DialogResult.OK &&
                File.Exists(fileName))
            {
                Type pixelDataType;
                int  snapshot = 1;
                bool hasNegativePixels;

                bool loaded = FITSHelper.LoadFloatingPointFitsFile(
                    fileName,
                    null,
                    out pixels,
                    out medianValue,
                    out pixelDataType,
                    out exposureSeconds,
                    out hasNegativePixels,
                    delegate(BasicHDU imageHDU)
                {
                    if (
                        imageHDU.Axes.Count() != 2 ||
                        imageHDU.Axes[0] != TangraContext.Current.FrameHeight ||
                        imageHDU.Axes[1] != TangraContext.Current.FrameWidth)
                    {
                        m_VideoController.ShowMessageBox(
                            "Selected image has a different frame size from the currently loaded video.", "Tangra",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);

                        return(false);
                    }

                    bool isFloatingPointImage = false;
                    Array dataArray           = (Array)imageHDU.Data.DataArray;
                    object entry = dataArray.GetValue(0);
                    if (entry is float[])
                    {
                        isFloatingPointImage = true;
                    }
                    else if (entry is Array)
                    {
                        isFloatingPointImage = ((Array)entry).GetValue(0) is float;
                    }

                    HeaderCard imagesCombinedCard = imageHDU.Header.FindCard("SNAPSHOT");
                    if (imagesCombinedCard != null)
                    {
                        int.TryParse(imagesCombinedCard.Value, out snapshot);
                    }


                    if (!isFloatingPointImage && imageHDU.BitPix != 16)
                    {
                        if (m_VideoController.ShowMessageBox(
                                "Selected image data type may not be compatible with the currently loaded video. Do you wish to continue?", "Tangra",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No)
                        {
                            return(false);
                        }
                    }

                    float usedEncodingGamma    = float.NaN;
                    string usedGammaString     = null;
                    HeaderCard tangraGammaCard = imageHDU.Header.FindCard("TANGAMMA");
                    if (tangraGammaCard != null &&
                        float.TryParse(tangraGammaCard.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out usedEncodingGamma))
                    {
                        usedGammaString = usedEncodingGamma.ToString("0.0000", CultureInfo.InvariantCulture);
                    }

                    string gammaUsageError = null;
                    string currGammaString = TangraConfig.Settings.Generic.ReverseGammaCorrection
                                                        ? TangraConfig.Settings.Photometry.EncodingGamma.ToString("0.0000", CultureInfo.InvariantCulture)
                                                        : null;
                    if (TangraConfig.Settings.Generic.ReverseGammaCorrection && currGammaString != null && usedGammaString == null)
                    {
                        gammaUsageError = string.Format("Selected image hasn't been Gamma corrected while the current video uses a gamma of {0}.", currGammaString);
                    }
                    else if (!TangraConfig.Settings.Generic.ReverseGammaCorrection && usedGammaString != null && currGammaString == null)
                    {
                        gammaUsageError = string.Format("Selected image has been corrected for Gamma of {0} while the current video doesn't use gamma correction.", usedGammaString);
                    }
                    else if (TangraConfig.Settings.Generic.ReverseGammaCorrection && !string.Equals(currGammaString, usedGammaString))
                    {
                        gammaUsageError = string.Format("Selected image has been corrected for Gamma of {0} while the current video uses a gamma of {1}.", usedGammaString, currGammaString);
                    }

                    if (gammaUsageError != null)
                    {
                        if (m_VideoController.ShowMessageBox(gammaUsageError + " Do you wish to continue?", "Tangra", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No)
                        {
                            return(false);
                        }
                    }

                    TangraConfig.KnownCameraResponse usedCameraResponse = TangraConfig.KnownCameraResponse.Undefined;
                    string usedCameraResponseString  = null;
                    int usedCameraResponseInt        = 0;
                    HeaderCard tangraCamResponseCard = imageHDU.Header.FindCard("TANCMRSP");
                    if (tangraCamResponseCard != null &&
                        int.TryParse(tangraCamResponseCard.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out usedCameraResponseInt))
                    {
                        usedCameraResponse       = (TangraConfig.KnownCameraResponse)usedCameraResponseInt;
                        usedCameraResponseString = usedCameraResponse.ToString();
                    }

                    string cameraResponseUsageError = null;
                    string currCameraResponseString = TangraConfig.Settings.Generic.ReverseCameraResponse
                                                        ? TangraConfig.Settings.Photometry.KnownCameraResponse.ToString()
                                                        : null;
                    if (TangraConfig.Settings.Generic.ReverseCameraResponse && currCameraResponseString != null && usedCameraResponseString == null)
                    {
                        cameraResponseUsageError = string.Format("Selected image hasn't been corrected for camera reponse while the current video uses a camera response correction for {0}.", currCameraResponseString);
                    }
                    else if (!TangraConfig.Settings.Generic.ReverseCameraResponse && usedCameraResponseString != null && currCameraResponseString == null)
                    {
                        cameraResponseUsageError = string.Format("Selected image has been corrected for camera response of {0} while the current video doesn't use camera response correction.", usedCameraResponseString);
                    }
                    else if (TangraConfig.Settings.Generic.ReverseCameraResponse && !string.Equals(currCameraResponseString, usedCameraResponseString))
                    {
                        cameraResponseUsageError = string.Format("Selected image has been corrected for camera reponse of {0} while the current video uses a camera response correction for {1}.", usedCameraResponseString, currCameraResponseString);
                    }

                    if (cameraResponseUsageError != null)
                    {
                        if (m_VideoController.ShowMessageBox(cameraResponseUsageError + " Do you wish to continue?", "Tangra", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No)
                        {
                            return(false);
                        }
                    }

                    return(true);
                });

                imagesCombined = snapshot;
                return(loaded);
            }

            return(false);
        }
예제 #12
0
        //public static FITSData LoadFitsFile(string fileName, BasicHDU hdu, Array pixels, IFITSTimeStampReader timeStampReader, int negativePixelCorrection)
        //{

        //}

        public static FITSData LoadFitsFile(string fileName, IFITSTimeStampReader timeStampReader, int negativePixelCorrection)
        {
            var rv = new FITSData();

            Fits fitsFile = new Fits();

            using (BufferedFile bf = new BufferedFile(fileName, FileAccess.Read, FileShare.ReadWrite))
            {
                fitsFile.Read(bf);

                rv.HDU = fitsFile.GetHDU(0);

                rv.Width  = rv.HDU.Axes[1];
                rv.Height = rv.HDU.Axes[0];

                Array pixelsArray = (Array)rv.HDU.Data.DataArray;

                rv.PixelStats           = new PixelStats();
                rv.PixelStats.BZero     = GetBZero(rv.HDU);
                rv.PixelStats.RawBitPix = rv.HDU.BitPix;

                uint mask = (uint)(((uint)1 << rv.PixelStats.RawBitPix) - 1);
                rv.PixelStats.BitPix = rv.PixelStats.RawBitPix;
                if (rv.PixelStats.BitPix < 0)
                {
                    /* float and double are -32 and -64 respectively */
                    // Pretending float data is 16 bit. This is the maximum currently supported by Tangra
                    // Not using a mask here, and the pixel values will be converted further down
                    mask = 0;
                }

                rv.PixelsFlat = Load16BitImageData(pixelsArray, rv.Height, rv.Width, rv.PixelStats.BZero - negativePixelCorrection, mask,
                                                   out rv.PixelStats.MedianPixelValue, out rv.PixelStats.PixelType,
                                                   out rv.PixelStats.HasNegativePixels, out rv.PixelStats.MinPixelValue,
                                                   out rv.PixelStats.MaxPixelValue);


                rv.PixelStats.BitPix = GetBppForMaxPixelValue(rv.PixelStats.MaxPixelValue);


                if (rv.PixelStats.BitPix == 32)
                {
                    // Tangra only supports up to 16 bit so convert down to 16 bit
                    int shift = Math.Max(0, (int)Math.Ceiling(Math.Abs(rv.HDU.BitPix) / 16.0) - 1);

                    for (int y = 0; y < rv.Height; y++)
                    {
                        for (int x = 0; x < rv.Width; x++)
                        {
                            rv.PixelsFlat[x + y * rv.Width] = rv.PixelsFlat[x + y * rv.Width] >> shift;
                        }
                    }

                    rv.PixelStats.BitPix = 16;
                }
            }


            // Read Timestamp & Exposure
            if (timeStampReader != null)
            {
                bool isMidPoint;
                rv.Timestamp = timeStampReader.ParseExposure(fileName, rv.HDU.Header, out isMidPoint, out rv.Exposure);
            }


            // Read card from header
            rv.Cards = new Dictionary <string, string>();
            var cursor = rv.HDU.Header.GetCursor();

            while (cursor.MoveNext())
            {
                HeaderCard card = rv.HDU.Header.FindCard((string)cursor.Key);
                if (card != null && !string.IsNullOrWhiteSpace(card.Key) && card.Key != "END")
                {
                    if (rv.Cards.ContainsKey(card.Key))
                    {
                        rv.Cards[card.Key] += "\r\n" + card.Value;
                    }
                    else
                    {
                        rv.Cards.Add(card.Key, card.Value);
                    }
                }
            }

            return(rv);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="HeaderSet">
 /// Заголовок галереи изображений.
 /// </param>
 /// <param name="ItemsSet">
 /// Набор изображений для галереи — не меньше 1, не больше 5.
 /// </param>
 /// <param name="FooterSet">
 /// Кнопки под галереей изображений.
 /// </param>
 public ItemsCardList(HeaderCard HeaderSet, CardItems[] ItemsSet, FooterCard FooterSet)
 {
     header = HeaderSet;
     items  = ItemsSet;
     footer = FooterSet;
 }
예제 #14
0
 public HeaderEntry(HeaderCard card)
 {
     Card = card;
 }