Example #1
0
        internal void CreateMap(AstroImage image, Rectangle frame, StarMapInternalConfig config)
        {
            m_FullWidth  = image.Width;
            m_FullHeight = image.Height;
            m_Pixelmap   = image.Pixelmap;

            InitCreateMap();
            CreateMap(config);
        }
Example #2
0
        public void PlateSolve(PlateSolveTesterConfig config)
        {
            var pixelMap = new Pixelmap(config.Width, config.Height, config.BitPix, config.Pixels, null, null);
            var image = new AstroImage(pixelMap);

            StarMap starMap = new StarMap(
                TangraConfig.Settings.Astrometry.PyramidRemoveNonStellarObject,
                TangraConfig.Settings.Astrometry.MinReferenceStarFWHM,
                TangraConfig.Settings.Astrometry.MaxReferenceStarFWHM,
                TangraConfig.Settings.Astrometry.MaximumPSFElongation,
                TangraConfig.Settings.Astrometry.LimitReferenceStarDetection);

            Rectangle excludeRect = new Rectangle(config.OSDRectToExclude.X, config.OSDRectToExclude.Y, config.OSDRectToExclude.Width, config.OSDRectToExclude.Height);
            Rectangle includeRect = new Rectangle(config.RectToInclude.X, config.RectToInclude.Y, config.RectToInclude.Width, config.RectToInclude.Height);

            starMap.FindBestMap(
                StarMapInternalConfig.Default,
                image,
                excludeRect,
                includeRect,
                config.LimitByInclusion);

            var facade = new StarCatalogueFacade(TangraConfig.Settings.StarCatalogue);
            var catalogueStars = facade.GetStarsInRegion(
                config.RADeg,
                config.DEDeg,
                (config.ErrFoVs + 1.0) * config.PlateConfig.GetMaxFOVInArcSec() / 3600.0,
                config.LimitMagn,
                config.Epoch);

            var distBasedMatcher = new DistanceBasedAstrometrySolver(
                new MockedOperationNotifier(),
                config.PlateConfig,
                TangraConfig.Settings.Astrometry,
                catalogueStars, config.DetermineAutoLimitMagnitude);

            distBasedMatcher.SetMinMaxMagOfStarsForAstrometry(config.PyramidMinMag, config.LimitMagn);
            distBasedMatcher.SetMinMaxMagOfStarsForPyramidAlignment(config.PyramidMinMag, config.PyramidMaxMag);

            distBasedMatcher.InitNewMatch(starMap, PyramidMatchType.PlateSolve, null);

            distBasedMatcher.InitNewFrame(starMap);

            distBasedMatcher.SetManuallyIdentifiedHints(new Dictionary<PSFFit, IStar>());

            LeastSquareFittedAstrometry astrometricFit;
            PerformMatchResult result = distBasedMatcher.PerformMatch(out astrometricFit);
        }
        public frmRunMultiFrameSpectroscopy(IFramePlayer framePlayer, VideoSpectroscopyOperation videoOperation, AstroImage astroImage)
            : this()
        {
            m_VideoOperation = videoOperation;
            m_AstroImage = astroImage;

            nudNumberMeasurements.Maximum = framePlayer.Video.LastFrame - framePlayer.CurrentFrameIndex;
            nudNumberMeasurements.SetNUDValue(Math.Min(200, nudNumberMeasurements.Maximum));
            nudAreaWing.SetNUDValue(Math.Min(videoOperation.MeasurementAreaWing, nudAreaWing.Maximum));
            nudBackgroundWing.SetNUDValue(Math.Min(videoOperation.BackgroundAreaWing, nudBackgroundWing.Maximum));
            cbxBackgroundMethod.SelectedIndex = 1; /* Median */
            cbxCombineMethod.SelectedIndex = 1; /* Median */
            nudExposureSec.SetNUDValue(astroImage.Pixelmap.FrameState.ExposureInMilliseconds / 1000.0f);

            m_Initialised = true;
        }
Example #4
0
        public PlateObjectResolver(
			IAstrometryController astrometryController,
			IVideoController videoController,
			AstroImage image,
			LeastSquareFittedAstrometry impSol,
			List<IStar> stars,
			double maxMagForAstrometry)
        {
            m_AstrometryController = astrometryController;
            m_VideoController = videoController;

            m_Image = image;
            m_Astrometry = impSol;
            m_Stars = stars;
            m_MaxMagForAstrometry = maxMagForAstrometry;
        }
Example #5
0
        public void InitializeStarMapButDontProcess(StarMapInternalConfig config, AstroImage image, Rectangle osdFrameToExclude, Rectangle frameToInclude, bool limitByInclusion)
        {
            m_FullWidth         = image.Width;
            m_FullHeight        = image.Height;
            m_Pixelmap          = image.Pixelmap;
            m_OSDFrameToExclude = osdFrameToExclude;
            m_FrameToInclude    = frameToInclude;
            m_LimitByInclusion  = limitByInclusion;

            try
            {
                m_AverageBackgroundNoise = 0;
                InitCreateMap();
            }
            finally
            {
                m_PerformanceWatch.Stop();
            }
        }
        internal void ProcessFrame(int frameNo, AstroImage astroImage, DateTime timeStamp, float exposureSeconds)
        {
            string fileName = Path.GetFullPath(string.Format("{0}\\{1}_{2}.fit", m_FolderName, frameNo.ToString().PadLeft(5, '0'), timeStamp.ToString("yyyy-MMM-dd_HHmmss_fff")));
            if (m_UsesROI)
            {
                uint[] subpixels = new uint[m_RegionOfInterest.Width * m_RegionOfInterest.Height];

                for (int y = 0; y < m_RegionOfInterest.Height; y++)
                {
                    for (int x = 0; x < m_RegionOfInterest.Width; x++)
                    {
                        subpixels[y * m_RegionOfInterest.Width + x] = astroImage.Pixelmap.Pixels[(m_RegionOfInterest.Top + y) * m_FrameWidth + m_RegionOfInterest.Left + x];
                    }
                }

                SaveFitsFrame(fileName, m_RegionOfInterest.Width, m_RegionOfInterest.Height, subpixels, timeStamp, exposureSeconds);
            }
            else
            {
                SaveFitsFrame(fileName, m_RegionOfInterest.Width, m_RegionOfInterest.Height, astroImage.Pixelmap.Pixels, timeStamp, exposureSeconds);
            }
        }
Example #7
0
        protected PSFFit GetBestFitGaussian(AstroImage astroImage, TrackedObject guidingStar)
        {
            // Try all fits from 5 to 15. Find the one with the highest peak, then do a fit around this area with the configured psf matrix size
            uint[,] pixels = astroImage.GetMeasurableAreaPixels((int)guidingStar.LastFrameX, (int)guidingStar.LastFrameY);

            PSFFit bestGaussian = null;

            if (!guidingStar.OriginalObject.IsCloseToOtherStars)
            {
                // There is only one object in the area, just do a whide fit followed by a fit with the selected matrix size
                PSFFit gaussian = new PSFFit((int) guidingStar.LastFrameX, (int) guidingStar.LastFrameY);
                gaussian.Fit(pixels, pixels.GetLength(0));
                if (gaussian.IsSolved)
                {
                    bestGaussian = gaussian;
                }
            }
            else
            {
                // There is more than one object in the area. We need a smarter way to find the one we need.
                if (guidingStar.IsOccultedStar)
                {
                    for (int matSize = 5; matSize < 15; matSize += 2)
                    {
                        PSFFit gaussian = new PSFFit((int) guidingStar.LastFrameX, (int) guidingStar.LastFrameY);
                        gaussian.Fit(pixels, matSize);
                        if (gaussian.IsSolved)
                        {
                            if (bestGaussian == null ||
                                bestGaussian.IMax < gaussian.IMax)
                            {
                                bestGaussian = gaussian;
                            }
                        }
                    }
                }
                else
                {
                    PSFFit gaussian = new PSFFit((int) guidingStar.LastFrameX, (int) guidingStar.LastFrameY);
                    gaussian.Fit(pixels, guidingStar.PsfFitMatrixSize);
                }
            }

            if (bestGaussian != null)
            {
                pixels = astroImage.GetMeasurableAreaPixels((int)bestGaussian.XCenter, (int)bestGaussian.YCenter);
                bestGaussian = new PSFFit((int)bestGaussian.XCenter, (int)bestGaussian.YCenter);
                bestGaussian.Fit(pixels, guidingStar.PsfFitMatrixSize);
            }

            return bestGaussian;
        }
        internal frmAddOrEditSingleTarget(int objectId, TrackedObjectConfig selectedObject, LCStateMachine state, VideoController videoController)
        {
            InitializeComponent();

            m_VideoController = videoController;

            m_AutocenteredApertureAvailable = true;

            Text = "Edit Object";

            btnAdd.Text = "Save";
            btnDontAdd.Text = "Cancel";
            btnDelete.Visible = true;
            m_IsEdit = true;

            m_ObjectId = objectId;
            m_State = state;
            m_AstroImage = m_State.VideoOperation.m_StackedAstroImage;

            ObjectToAdd = selectedObject;

            if (selectedObject.TrackingType != TrackingType.ComparisonStar)
                nudFitMatrixSize.SetNUDValue(selectedObject.PsfFitMatrixSize);

            m_Center = new ImagePixel(
                selectedObject.OriginalFieldCenterX,
                selectedObject.OriginalFieldCenterY);

            if (ObjectToAdd.PositionTolerance > 0)
                nudPositionTolerance.SetNUDValue((decimal)ObjectToAdd.PositionTolerance);

            Initialize();

            if (!selectedObject.IsWeakSignalObject && !selectedObject.IsFixedAperture)
            {
                int matrixSize = selectedObject.PsfFitMatrixSize;
                GetFitInMatrix(selectedObject.Gaussian, ref matrixSize, selectedObject.ApertureInPixels);
                selectedObject.PsfFitMatrixSize = matrixSize;
            }
            else
            {
                m_ProcessingPixels = m_AstroImage.GetMeasurableAreaPixels(m_Center);
                m_DisplayPixels = m_AstroImage.GetMeasurableAreaDisplayBitmapPixels(m_Center);

                m_FWHM = 6;
                m_Gaussian = null;
                m_X0 = selectedObject.ApertureMatrixX0;
                m_Y0 = selectedObject.ApertureMatrixY0;
                dx = selectedObject.ApertureDX;
                dy = selectedObject.ApertureDY;

                PlotSingleTargetPixels();

                nudAperture1.SetNUDValue((decimal) Math.Round(ObjectToAdd.ApertureInPixels, 2));
            }

            SetHeightAndType();

            if (selectedObject.TrackingType == TrackingType.GuidingStar)
                SelectedObjectType = TrackingType.GuidingStar;
            else if (selectedObject.TrackingType == TrackingType.OccultedStar)
                SelectedObjectType = TrackingType.OccultedStar;
        }
Example #9
0
        public void NextFrame(int frameNo, MovementType movementType, bool isLastFrame, AstroImage astroImage, int firstFrameInIntegrationPeriod, string frameFileName)
        {
            m_CurrentAstroImage = astroImage;
            m_FrameNumber = frameNo;
            TangraContext.Current.CrashReportInfo.FrameNumber = frameNo;

            if (m_Running)
            {
                if (m_FramesDone < m_NumFrames)
                {
                    Pixelmap currPixelmap = astroImage.Pixelmap;
                    if (m_FramesDone == 0)
                        m_AveragedData = new float[currPixelmap.Width, currPixelmap.Height];

                    for (int x = 0; x < currPixelmap.Width; x++)
                        for (int y = 0; y < currPixelmap.Height; y++)
                        {
                            m_AveragedData[x, y] += currPixelmap[x, y];
                        }

                    m_FramesDone++;
                    m_ControlPanel.SetProgress(m_FramesDone);

                    if (m_FramesDone == m_NumFrames)
                    {
                        // Averaging
                        for (int x = 0; x < currPixelmap.Width; x++)
                        for (int y = 0; y < currPixelmap.Height; y++)
                        {
                            m_AveragedData[x, y] = (m_AveragedData[x, y] / (ulong)m_FramesDone);
                        }

                        m_ControlPanel.SetStopped();

                        string fileName = string.Format("{0}_{1}.fit", Path.GetFileNameWithoutExtension(m_VideoController.CurrentVideoFileName), m_FrameType.ToString());

                        if (m_VideoController.ShowSaveFileDialog(
                            "Save " + m_FrameType.ToString() + " fame",
                            "FITS Image (*.fit)|*.fit",
                            ref fileName) == DialogResult.OK)
                        {
                            string notes = string.Format("{0} generated from {1}", m_FrameType.ToString(), Path.GetFileNameWithoutExtension(m_VideoController.CurrentVideoFileName));

                            SaveDarkOrFlatFrame(fileName, currPixelmap.Width, currPixelmap.Height, notes, m_AveragedData, m_ExposureSeconds, m_NumFrames);
                        }

                        m_Running = false;
                        m_VideoController.StopVideo();

                        if (m_FrameType == FrameType.Dark) UsageStats.Instance.DarkFramesProduced++;
                        if (m_FrameType == FrameType.MasterFlat) UsageStats.Instance.FlatFramesProduced++;

                        UsageStats.Instance.Save();
                    }
                }
            }
        }
        private void GenerateFrame(Pixelmap pixmap, List<IStar> stars, ModelConfig modelConfig)
        {
            var mea = new MeasurementsHelper(
                pixmap.BitPixCamera,
                TangraConfig.BackgroundMethod.BackgroundMedian,
                TangraConfig.Settings.Photometry.SubPixelSquareSize,
                TangraConfig.Settings.Photometry.Saturation.GetSaturationForBpp(pixmap.BitPixCamera, pixmap.MaxSignalValue));

            float apertureSize = APERTURE;
            float annulusInnerRadius = (GAP + APERTURE) / APERTURE;
            int annulusMinPixels = (int)(Math.PI * (Math.Pow(ANNULUS + GAP + APERTURE, 2) - Math.Pow(GAP + APERTURE, 2)));

            mea.SetCoreProperties(annulusInnerRadius, annulusMinPixels, CorePhotometrySettings.Default.RejectionBackgroundPixelsStdDev, 2 /* TODO: This must be configurable */);

            var measurements = new Dictionary<IStar, double>();

            foreach (IStar star in stars)
            {
                double x, y;

                GetOnPlateCoordinates(star.RADeg, star.DEDeg, modelConfig, out x, out y);

                if (x < 0 || x > modelConfig.FrameWidth || y < 0 || y > modelConfig.FrameHeight)
                    continue;

                float starMag = GetStarMag(star, modelConfig.PhotometricFilter);
                float iMax = ModelStarAmplitude(star, starMag, modelConfig, pixmap.BitPixCamera, pixmap.MaxSignalValue);

                if (!float.IsNaN(iMax))
                {
                    VideoModelUtils.GenerateStar(pixmap, (float)x, (float)y, (float)modelConfig.FWHM, iMax, 0 /*Use Gaussian */);

                    if (modelConfig.CheckMagnitudes)
                    {
                        var image = new AstroImage(pixmap);
                        uint[,] data = image.GetMeasurableAreaPixels((int)x, (int)y, 17);
                        uint[,] backgroundPixels = image.GetMeasurableAreaPixels((int)x, (int)y, 35);

                        PSFFit fit = new PSFFit((int)x, (int)y);
                        fit.Fit(data);

                        var result = mea.MeasureObject(new ImagePixel(x, y), data, backgroundPixels, pixmap.BitPixCamera,
                            TangraConfig.PreProcessingFilter.NoFilter,
                            TangraConfig.PhotometryReductionMethod.AperturePhotometry, TangraConfig.PsfQuadrature.NumericalInAperture,
                            TangraConfig.PsfFittingMethod.DirectNonLinearFit,
                            apertureSize, modelConfig.FWHM, (float)modelConfig.FWHM,
                            new FakeIMeasuredObject(fit),
                            null, null,
                            false);

                        if (result == NotMeasuredReasons.TrackedSuccessfully && !mea.HasSaturatedPixels)
                        {
                            // Add value for fitting
                            measurements.Add(star, mea.TotalReading - mea.TotalBackground);
                        }
                    }
                }
            }

            if (modelConfig.CheckMagnitudes)
                CalculateGagnitudeFit(measurements, modelConfig.BVSlope);
        }
Example #11
0
        public static Dictionary<ImagePixel, double> LocateHotPixels(AstroImage image, uint[,] model, uint modelMedian)
        {
            var rv = new Dictionary<ImagePixel, double>();
            if (s_NumSamplesCombined > 0)
            {
                int width = image.Pixelmap.Width;
                int height = image.Pixelmap.Height;
                uint abv = model[3, 3] - modelMedian;
                uint minPeakLevel = (uint)(modelMedian + PEAK_PIXEL_LEVEL_REQUIRED * abv);
                EnumeratePeakPixels(image.Pixelmap.GetPixelsCopy(), width, height, minPeakLevel, Rectangle.Empty,
                    (x, y, z) =>
                    {
                        if (x >= 3 && x < width - 3 && y >= 3 && y < height - 3)
                        {
                            var newPix = new ImagePixel((int) z, x, y);
                            if (!rv.Keys.ToArray().Any(p => p.DistanceTo(newPix) < 5))
                                rv.Add(newPix, long.MinValue);
                        }

                    });

                foreach (ImagePixel center in rv.Keys.ToArray())
                {
                    uint[,] testArea = image.GetPixelsArea(center.X, center.Y, 7);
                    var score = ScoreArea(testArea);
                    rv[center] = score.Item1;
                }

                var positions = rv.Keys.ToArray();
                var scores = rv.Values.ToArray();
                Array.Sort(scores, positions);
                s_Candidates = positions;
                s_CandidateScores = scores;
            }

            return rv;
        }
Example #12
0
        public static void PSFPhotometry(FitInfo astrometricFit, List<IStar> catalogueStars, AstroImage currentAstroImage, Rectangle osdRectToExclude, Rectangle rectToInclude, bool limitByInclusion)
        {
            StringBuilder output = new StringBuilder();

            foreach (PlateConstStarPair pair in astrometricFit.AllStarPairs)
            {
                uint[,] data = currentAstroImage.GetMeasurableAreaPixels(
                    (int)Math.Round(pair.x), (int)Math.Round(pair.y), 9);

                if (limitByInclusion && !rectToInclude.Contains((int)pair.x, (int)pair.y)) continue;
                if (!limitByInclusion && osdRectToExclude.Contains((int)pair.x, (int)pair.y)) continue;

                PSFFit gaussian = new PSFFit((int)Math.Round(pair.x), (int)Math.Round(pair.y));
                gaussian.Fit(data);
                if (gaussian.IsSolved)
                {
                    IStar star = catalogueStars.Find(s => s.StarNo == pair.StarNo);
                    if (star != null &&
                        !double.IsNaN(star.MagR))
                    {
                        output.AppendLine(string.Format("{0}, {1}, {2}, {3}, {4}", pair.StarNo, star.MagR, gaussian.R0, gaussian.IMax, gaussian.I0));
                    }
                }
            }

            File.WriteAllText(@"C:\PSF_Photo.csv", output.ToString());
        }
        internal frmAddOrEditMutualEventsTarget(int objectId, TrackedObjectConfig selectedObject, LCStateMachine state, VideoController videoController)
        {
            InitializeComponent();

            m_VideoController = videoController;

            Text = "Edit 'Mutual Event' Target";
            btnAdd.Text = "Save";
            btnDontAdd.Text = "Cancel";
            btnDelete.Visible = true;
            m_IsEdit = true;

            m_ObjectId = objectId;
            m_State = state;
            m_AstroImage = m_VideoController.GetCurrentAstroImage(false);

            ObjectToAdd = selectedObject;

            float? commonAperture = m_State.MeasuringApertures.Count > 0
                ? m_State.MeasuringApertures[0] :
                (float?)null;

            m_Aperture = commonAperture;
            m_Aperture1 = commonAperture;
            m_Aperture2 = commonAperture;

            m_Center = new ImagePixel(selectedObject.ApertureStartingX, selectedObject.ApertureStartingY);
            m_OriginalCenter = new ImagePixel(selectedObject.ApertureStartingX, selectedObject.ApertureStartingY);

            if (selectedObject.ProcessInPsfGroup)
            {
                m_GroupId = selectedObject.GroupId;

                List<TrackedObjectConfig> otherGroupedObjects = state.m_MeasuringStars.Where(x => m_GroupId >= 0 && x.GroupId == m_GroupId && x != selectedObject).ToList();
                if (otherGroupedObjects.Count == 1)
                {
                    ObjectToAdd2 = otherGroupedObjects[0];
                    m_ObjectId2 = state.m_MeasuringStars.IndexOf(ObjectToAdd2);
                }
            }
            else
            {
                ObjectToAdd2 = null;
                m_GroupId = objectId;
                // If we are to use a second object, it should have the next available Id
                m_ObjectId2 = state.m_MeasuringStars.Count;
            }

            m_EditingOccultedStar = selectedObject.IsOcultedStar();

            Initialise();
        }
Example #14
0
        public int FindBestMap(
            StarMapInternalConfig config, AstroImage image,
            Rectangle osdFrameToExclude, Rectangle frameToInclude, bool limitByInclusion)
        {
            m_Config = config;

            m_PerformanceWatch.Reset();
            m_PerformanceWatch.Start();

            m_FullWidth  = image.Width;
            m_FullHeight = image.Height;
            m_Pixelmap   = image.Pixelmap;

            m_OSDFrameToExclude = osdFrameToExclude;
            m_FrameToInclude    = frameToInclude;
            m_LimitByInclusion  = limitByInclusion;

            int  optimumStarsInField = config.OptimumStarsInField ?? (TangraConfig.Settings != null ? (int)TangraConfig.Settings.Astrometry.PyramidOptimumStarsToMatch : 25);
            uint maxSignalValue      = config.CustomMaxSignalValue ?? m_Pixelmap.MaxSignalValue;

            m_AverageBackgroundNoise = maxSignalValue;

            int MIN_INTENSITY        = config.IsFITSFile ? 1 : 5;
            int MAX_INTENSITY        = config.IsFITSFile ? 1000 : 100;
            int INTENSITY_LARGE_STEP = config.IsFITSFile ? 50 : 5;
            int INTENSITY_SMALL_STEP = config.IsFITSFile ? 2 : 5;

            if (config.CustomOptimumStarsValue.HasValue)
            {
                optimumStarsInField = config.CustomOptimumStarsValue.Value;
            }

            double snRatio = config.IsFITSFile ? 0.005 : 0.15;

            try
            {
                int  featuresThisRun    = 0;
                int  featuresLastRun    = 0;
                bool tryForOptimumStars = optimumStarsInField > config.MinStarsInField;

                List <StarMapFeature> bestMapFeatures = new List <StarMapFeature>();

                int intensity = MAX_INTENSITY;
                int tolerance = config.StarMapperTolerance;
                InitCreateMap();
                do
                {
                    if (intensity > 2 * INTENSITY_LARGE_STEP)
                    {
                        intensity -= INTENSITY_LARGE_STEP;
                    }
                    else
                    {
                        intensity -= INTENSITY_SMALL_STEP;
                    }

                    uint backgroundThreshold = (uint)Math.Round(maxSignalValue * (intensity * 1.0 / MAX_INTENSITY));

                    if (backgroundThreshold < config.MinStarMapThreashold)
                    {
                        break;
                    }
                    if (backgroundThreshold < snRatio * (maxSignalValue - m_AverageBackgroundNoise))
                    {
                        break;
                    }

                    try
                    {
                        CreateMap(backgroundThreshold, config);
                    }
                    catch (StarMapException)
                    {
                        backgroundThreshold = (uint)Math.Round(maxSignalValue * ((intensity + INTENSITY_LARGE_STEP) * 1.0 / MAX_INTENSITY));
                        snRatio             = (double)(backgroundThreshold - 1.0) / (maxSignalValue - m_AverageBackgroundNoise);
                        intensity          += 2 * INTENSITY_LARGE_STEP;
                        continue;
                    }

                    if (m_Features.Count > 2.5 * optimumStarsInField)
                    {
                        m_Features.Sort((x, y) => y.PixelCount.CompareTo(x.PixelCount));
                        m_Features = m_Features.Take(2 * optimumStarsInField).ToList();
                    }

                    featuresLastRun = featuresThisRun;
                    featuresThisRun = m_Features.Count;

                    if (tryForOptimumStars)
                    {
                        if (
                            featuresLastRun <= optimumStarsInField &&
                            featuresThisRun >= optimumStarsInField &&
                            featuresLastRun > 0.5 * optimumStarsInField &&
                            featuresThisRun < 1.5 * optimumStarsInField)
                        {
                            if (optimumStarsInField - featuresLastRun <=
                                featuresThisRun - optimumStarsInField)
                            {
                                break;
                            }
                            else
                            {
                                bestMapFeatures.Clear();
                                bestMapFeatures.AddRange(m_Features);
                                break;
                            }
                        }
                        else
                        {
                            if (featuresThisRun >= 1.5 * optimumStarsInField)
                            {
                                // We couldn't fit in the optimum star range, so not trying to any more
                                tryForOptimumStars = false;
                            }
                        }
                    }

                    bestMapFeatures.Clear();
                    bestMapFeatures.AddRange(m_Features);

                    if (featuresThisRun > config.MaxStarsInField)
                    {
                        break;
                    }

                    if (m_Features.Count > config.MinStarsInField &&
                        featuresThisRun > featuresLastRun)
                    {
                        bool allNewFeaturesHaveOnePixel = true;
                        foreach (StarMapFeature feature in m_Features)
                        {
                            if (feature.Generation == 1 &&
                                feature.m_Pixels.Count > 1)
                            {
                                allNewFeaturesHaveOnePixel = false;
                                break;
                            }
                        }

                        if (allNewFeaturesHaveOnePixel)
                        {
                            tolerance--;

                            if (tolerance <= 0 && !tryForOptimumStars)
                            {
                                break;
                            }
                        }
                    }

                    m_NoiseLevel = backgroundThreshold;
                }while (intensity > MIN_INTENSITY);

                if (m_ForceStellarObjectRequirements)
                {
                    ApplyPSFExclusionRulesToFeatures();
                }

                return(intensity);
            }
            finally
            {
                m_PerformanceWatch.Stop();

                if (TangraConfig.Settings.TraceLevels.PlateSolving.TraceVerbose())
                {
                    Trace.WriteLine(string.Format("StarMapGen: {0} ms, {1} features, {2} generations (tolerance = {3})",
                                                  m_PerformanceWatch.ElapsedMilliseconds,
                                                  m_Features.Count, m_Features.Count > 0 ? m_Features[0].Generation : 0,
                                                  config.StarMapperTolerance));
                }

                int lastGenMin = int.MaxValue;
                int thisGenMin = int.MaxValue;
                int lastGen    = int.MaxValue;
                for (int i = 0; i < m_Features.Count; i++)
                {
                    int            currMax = int.MinValue;
                    StarMapFeature ftr     = m_Features[i];
                    foreach (int intens in ftr.m_Pixels.Values)
                    {
                        if (intens > currMax)
                        {
                            currMax = intens;
                        }
                    }

#if ASTROMETRY_DEBUG
                    Trace.Assert(lastGen >= ftr.Generation);
#endif

                    if (lastGen > ftr.Generation)
                    {
                        lastGen    = ftr.Generation;
                        lastGenMin = thisGenMin;
                    }

#if ASTROMETRY_DEBUG
                    Trace.Assert(currMax < lastGenMin);
#endif

                    thisGenMin = currMax;
                }

                ReorderFeatureNumbersBasedOnIntensity();
            }
        }
Example #15
0
        private static Bitmap GetPreviewImage(Pixelmap currFrame)
        {
            CurrFrame = new AstroImage(currFrame);
            Bitmap image = currFrame.CreateDisplayBitmapDoNotDispose();

            if (OnDrawOverlays != null)
            {
                using (Graphics g = Graphics.FromImage(image))
                {
                    OnDrawOverlays.Invoke(g);
                    g.Save();
                }
            }

            return image;
        }
Example #16
0
 public SpectraReader(AstroImage image, float angleDegrees, float pixelValueCoefficient)
 {
     m_Image = image;
     m_Mapper = new RotationMapper(image.Width, image.Height, angleDegrees);
     m_SourceVideoFrame = new RectangleF(0, 0, image.Width, image.Height);
     m_PixelValueCoeff = pixelValueCoefficient;
 }
        internal frmAddOrEditMutualEventsTarget(int objectId, ImagePixel center, PSFFit gaussian, LCStateMachine state, VideoController videoController, bool tryAutoDoubleFind)
        {
            InitializeComponent();

            m_VideoController = videoController;
            m_TryAutoDoubleFind = tryAutoDoubleFind;

            Text = "Add 'Mutual Event' Target";
            btnAdd.Text = "Add";
            btnDontAdd.Text = "Don't Add";
            btnDelete.Visible = false;
            m_IsEdit = false;

            m_ObjectId = objectId;
            m_GroupId = objectId; // For Group Id we use the next object id
            m_State = state;
            m_AstroImage = m_VideoController.GetCurrentAstroImage(false);

            ObjectToAdd = null;
            ObjectToAdd2 = null;

            float? commonAperture = m_State.MeasuringApertures.Count > 0
                ? m_State.MeasuringApertures[0] :
                (float?)null;

            m_Aperture = commonAperture;
            m_Aperture1 = commonAperture;
            m_Aperture2 = commonAperture;

            m_Center = new ImagePixel(center);
            m_OriginalCenter = new ImagePixel(center);

            m_EditingOccultedStar = false;

            Initialise();
        }
        internal void ProcessFrame(int frameNo, AstroImage image)
        {
            bool isNewIntegrationPeroiod = IsNewIntegrationPeriod(frameNo, image);
            if (isNewIntegrationPeroiod)
            {
                string errors = null;
                if (m_FramesSoFar != m_IntegrationPeriod)
                {
                    m_VideoController.RegisterAAVConversionError();

                    // Normalize the value during  the conversion
                    for (int i = 0; i < m_CurrAavFramePixels.Length; i++)
                        m_CurrAavFramePixels[i] = (ushort)Math.Round(m_CurrAavFramePixels[i] * 1.0 * m_IntegrationPeriod / m_FramesSoFar);

                    errors = string.Format("{0} frames detected in the current interval", m_FramesSoFar);
                }

                string noiseSignatures = string.Empty;
                if (m_SigmaDict.Count >= m_IntegrationPeriod)
                {
                    for (int i = frameNo - m_IntegrationPeriod + 1; i <= frameNo; i++)
                    {
                        if (m_SigmaDict.ContainsKey(i))
                            noiseSignatures += string.Format("{0}={1:0.00};", i, m_SigmaDict[i]);
                    }
                }

                m_Recorder.AddVideoFrame(m_CurrAavFramePixels, true,
                    PreferredCompression.Lagarith16,
                    new AdvRecorder.AdvStatusEntry() { SystemErrors = errors, AdditionalStatusTags = new[] { "DATA", (object)(byte)m_FramesSoFar, noiseSignatures, (object)(int)0 } },
                    Adv.AdvImageData.PixelDepth16Bit);

                for (int i = 0; i < m_CurrAavFramePixels.Length; i++)
                    m_CurrAavFramePixels[i] = 0;

                m_FramesSoFar = 0;
            }

            bool copyAllOsdLines = isNewIntegrationPeroiod || frameNo == m_FirstIntegrationPeriodStartFrameId;

            for (int y = 0; y < m_Height; y++)
            {
                bool scale = false;
                if (y >= m_FirstVtiOsdLine && y <= m_LastVtiOsdLine)
                {
                    // NOTE: For first new frame - copy all lines
                    //       For any other frame - copy even/odd lines only
                    if (!copyAllOsdLines && (y % 2) == m_EndFieldParity)
                        continue;

                    scale = true;
                }

                for (int x = 0; x < m_Width; x++)
                {
                    if (scale)
                        m_CurrAavFramePixels[y * m_Width + x] = (ushort)(m_IntegrationPeriod * image.Pixelmap[x, y]);
                    else
                        m_CurrAavFramePixels[y * m_Width + x] += (ushort)(image.Pixelmap[x, y]);
                }
            }

            m_FramesSoFar++;
        }
Example #19
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            StarMapInternalConfig starMapConfig = StarMapInternalConfig.Default;

            if (rbAuto.Checked)
            {
                starMapConfig.OptimumStarsInField = (int) TangraConfig.Settings.Astrometry.PyramidOptimumStarsToMatch;
                starMapConfig.StarMapperTolerance = 2;
            }
            else
            {
                starMapConfig.OptimumStarsInField = -1;
                starMapConfig.StarMapperTolerance = trbarDepth.Value;
            }

            var starMap = new StarMap();

            var image = new AstroImage(m_InitialPixelmap);

            starMap.FindBestMap(
                starMapConfig,
                image,
                AstrometryContext.Current.OSDRectToExclude,
                AstrometryContext.Current.RectToInclude,
                AstrometryContext.Current.LimitByInclusion);

            AstrometryContext.Current.StarMap = starMap;
            AstrometryContext.Current.StarMapConfig = starMapConfig;

            m_VideoController.RedrawCurrentFrame(false, true);
        }
Example #20
0
 public AveragedFrame(AstroImage image)
 {
     m_Image = image;
 }
        private bool IsNewIntegrationPeriod(int frameNo, AstroImage image)
        {
            for (int x = 0; x < 32; x++)
                for (int y = 0; y < 32; y++)
                {
                    m_PrevPixels[x, y] = m_ThisPixels[x, y];
                }

            double sigmaSum = 0;

            for (int x = 0; x < 32; x++)
                for (int y = 0; y < 32; y++)
                {
                    m_ThisPixels[x, y] = (int)image.Pixelmap.Pixels[(x + m_TestRect.Left) + (y + m_TestRect.Top) * m_Width];

                    sigmaSum += Math.Abs(m_ThisPixels[x, y] - m_PrevPixels[x, y]) / 2.0;
                }

            if (frameNo == m_FirstIntegrationPeriodStartFrameId)
                return false;

            m_SigmaDict[frameNo] = sigmaSum / 1024;

            List<double> vals = m_SigmaDict.Values.Where(v => !double.IsNaN(v)).ToList();

            vals.Sort();

            double median = vals.Count % 2 == 1
                ? vals[vals.Count / 2]
                : (vals[vals.Count / 2] + vals[(vals.Count / 2) - 1]) / 2;

            List<double> residuals = vals.Select(v => Math.Abs(median - v)).ToList();

            double variance = residuals.Select(r => r * r).Sum();
            if (residuals.Count > 1)
            {
                variance = Math.Sqrt(variance / (residuals.Count - 1));
            }
            else
                variance = double.NaN;

            if (frameNo > m_FirstIntegrationPeriodStartFrameId + 2*m_IntegrationPeriod)
            {
                double residual = Math.Abs(median - m_SigmaDict[frameNo]);
                if (residual > variance)
                {
                    if (frameNo < m_NextExpectedIntegrationPeriodStartFrameId)
                    {
                        // New early integration period. This can be right if:
                        // 1) The old expected intergation frame has a smaller residual than this one
                        // 2) The next new frame under the new conditions passes the condition for a new integration frame
                        var nextExpectedResidual = GetFutureFrameNoisePatternResidual(m_NextExpectedIntegrationPeriodStartFrameId, median);
                        var nextNewExpectedResidual = GetFutureFrameNoisePatternResidual(frameNo + m_IntegrationPeriod, median);

                        if (nextExpectedResidual < residual && nextNewExpectedResidual > variance)
                        {
                            m_NextExpectedIntegrationPeriodStartFrameId = frameNo + m_IntegrationPeriod;
                            return true;
                        }
                    }
                    else if (frameNo == m_NextExpectedIntegrationPeriodStartFrameId)
                    {
                        m_NextExpectedIntegrationPeriodStartFrameId = frameNo + m_IntegrationPeriod;
                        return true;
                    }
                }
            }
            else
            {
                // NOTE: First 2 integration periods should have been identified correctly from the integration detection
                //       so for them only we don't apply the noise pattern check to allow it to get some more datapoints
                if (frameNo >= m_NextExpectedIntegrationPeriodStartFrameId)
                {
                    while (frameNo >= m_NextExpectedIntegrationPeriodStartFrameId)
                        m_NextExpectedIntegrationPeriodStartFrameId += m_IntegrationPeriod;

                    return true;
                }
            }

            return false;
        }
 public void EnsureStackedAstroImage()
 {
     if (m_StackedAstroImage == null)
     {
         m_ControlPanel.Cursor = Cursors.WaitCursor;
         try
         {
             m_StackedAstroImage = m_VideoController.GetCurrentAstroImage(false /*!LightCurveReductionContext.Instance.WindOrShaking*/);
         }
         finally
         {
             m_ControlPanel.Cursor = Cursors.Default;
         }
     }
 }
Example #23
0
        public StarMagnitudeFit(
			AstroImage astroImage,
			int bitPix,
			List<double> intencities,
			List<double> magnitudes,
			List<double> colours,
			List<IStar> starNumbers,
			List<PSFFit> psfGaussians,
			List<double> profileFittedAmplitudes,
			List<bool> saturatedFlags,
			double a, double b, double c, float encodingGamma, TangraConfig.KnownCameraResponse reverseCameraResponse, int excludedStars,
			TangraConfig.PreProcessingFilter filter, double empericalFWHM, 
			TangraConfig.PhotometryReductionMethod photometryReductionMethod, 
			TangraConfig.BackgroundMethod photometryBackgroundMethod,
			TangraConfig.PsfQuadrature psfQuadrature,
			TangraConfig.PsfFittingMethod psfFittingMethod,
            MeasurementsHelper measurer,
            float? aperture)
        {
            m_CurrentAstroImage = astroImage;
            m_BitPix = bitPix;
            m_Intencities = intencities;
            m_Magnitudes = magnitudes;
            m_Colours = colours;
            m_Residuals = new List<double>();
            m_StarNumbers = starNumbers;
            m_PSFGaussians = psfGaussians;
            m_EncodingGamma = encodingGamma;
            m_ReverseCameraResponse = reverseCameraResponse;
            m_ExcludedStars = excludedStars;
            m_SaturatedFlags = saturatedFlags;
            m_ProfileFittedAmplitudes = profileFittedAmplitudes;

            m_Sigma = 0;
            for (int i = 0; i < intencities.Count; i++)
            {
                double computed = a * -2.5 * Math.Log10(intencities[i]) + b * colours[i] + c;
                double diff = Math.Abs(computed - magnitudes[i]);
                m_Residuals.Add(diff);

                m_Sigma += diff*diff;
            }
            m_Sigma = Math.Sqrt(m_Sigma / (m_Residuals.Count - 1));

            m_Filter = filter;
            m_EmpericalFWHM = empericalFWHM;
            m_PhotometryReductionMethod = photometryReductionMethod;
            m_PhotometryBackgroundMethod = photometryBackgroundMethod;
            m_PsfQuadrature = psfQuadrature;
            m_PsfFittingMethod = psfFittingMethod;

            m_A = a;
            m_B = b;
            m_C = c;

            m_Measurer = measurer.Clone();
            m_MeasurementAperture = aperture;

            m_Sigma = 0;
            m_MinRes = double.MaxValue;
            m_MaxRes = double.MinValue;
            m_MinMag = double.MaxValue;
            m_MaxMag = double.MinValue;
            for (int i = 0; i < m_Residuals.Count; i++)
            {
                double res = m_Residuals[i];

                m_Sigma += res * res;
                if (m_MinRes > res) m_MinRes = res;
                if (m_MaxRes < res) m_MaxRes = res;

                double mag = m_Magnitudes[i];
                if (m_MinMag > mag) m_MinMag = mag;
                if (m_MaxMag < mag) m_MaxMag = mag;
            }

            m_Sigma = Math.Sqrt(m_Sigma / m_Residuals.Count);
        }
        public void NextFrame(int frameNo, MovementType movementType, bool isLastFrame, AstroImage astroImage, int firstFrameInIntegrationPeriod, string fileName)
        {
            m_AstroImage = astroImage;
            m_CurrFrameNo = frameNo;
            m_CurrFileName = fileName;

            TangraContext.Current.CrashReportInfo.FrameNumber = frameNo;

            if (m_Correcting)
                // Do not track or process the frame while correcting the tracking
                return;

            if (m_Configuring)
            {
                if (m_CurrFrameNo != frameNo) m_StackedAstroImage = null;
                if (frameNo != m_StateMachine.SelectedObjectFrameNo) m_StateMachine.SelectedObject = null;
            }

            if (m_Refining || m_Measuring)
            {
                if (m_VideoController.IsAstroAnalogueVideo && frameNo == 0)
                {
                    // Do not attempt refining on the first AAV frame as it has unique dynamic range and the refining is not going to work at all.
                }
                else
                {
                    m_Tracker.NextFrame(frameNo, astroImage);

                    if (!m_Tracker.IsTrackedSuccessfully) m_NumberFramesWithBadTracking++;

                    m_VideoController.SetDisplayHueBackgroundModeTargets(m_Tracker.TrackedObjects);

                    if (m_Refining)
                    {
                        if (m_Tracker.RefiningPercentageWorkLeft <= 0)
                        {
                            bool canSwitchFromRefiningToMeasuringNow = true;

                            if (m_VideoController.IsUsingSteppedAveraging)
                            {
                                // When using stepped averaging the measurements should start at the first frame of an integration 'step'
                                // which means we need to flip the switch from 'Refining' to 'Measuring' one frame before that
                                if (firstFrameInIntegrationPeriod + m_VideoController.FramesToIntegrate - 1 > frameNo)
                                {
                                    Trace.WriteLine(string.Format("Skipping frame {0}, waiting for the first frame in the next integration period to start measurments.", frameNo));
                                    canSwitchFromRefiningToMeasuringNow = false;
                                }
                            }

                            if (canSwitchFromRefiningToMeasuringNow)
                            {
                                float oneSigma;
                                m_AavNtpTimestampError = m_VideoController.AstroAnalogueVideoNormaliseNtpDataIfNeeded(out oneSigma);
                                m_AavNtpFitOneSigmaError = oneSigma;
                                // Begin measurements
                                m_Measuring = true;
                                m_Refining = false;

                                m_ProcessedFrames = 0;
                                m_UnsuccessfulFrames = 0;
                                m_PartiallySuccessfulFrames = 0;
                                m_StopWatch.Reset();
                                m_StopWatch.Start();

                                m_Tracker.BeginMeasurements(astroImage);

                                // IMPORTANT: The finalHeader must be changed as well if changing this
                                LCFile.NewOnTheFlyOutputFile(
                                    m_VideoController.CurrentVideoFileName,
                                    string.Format("Video ({0})", m_VideoController.CurrentVideoFileType),
                                    (byte)m_Tracker.TrackedObjects.Count, (float)m_Tracker.PositionTolerance,
                                    LightCurveReductionContext.Instance.LightCurveReductionType == LightCurveReductionType.TotalLunarReppearance);

                                m_MinFrame = uint.MaxValue;
                                m_MaxFrame = uint.MinValue;
                                m_TotalFrames = 0;
                                m_FirstMeasuredFrame = frameNo;

                                m_AverageFWHM = astroImage.GetAverageFWHM();

                                m_VideoController.StatusChanged("Measuring");
                            }
                        }
                    }
                }

                if (m_Measuring)
                {
                    if (!m_Tracker.IsTrackedSuccessfully &&
                         LightCurveReductionContext.Instance.StopOnLostTracking)
                    {
                        m_ControlPanel.StopMeasurements(ucLightCurves.StopReason.LostTracking);

                        if (TangraConfig.Settings.Tracking.PlaySound)
                            Console.Beep(800, 750);

                        if (TangraConfig.Settings.Tracking.PopUpOnLostTracking)
                            m_VideoController.ShowMessageBox(
                                "Use the mouse to pan the object apertures back to the object location and press 'Continue' to continue with the measurements. You can also do adjustments to the objects individually or skip the frame all together.",
                                "Tracking has been lost",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                        return;
                    }

                    m_ProcessedFrames++;
                    if (!m_Tracker.IsTrackedSuccessfully) m_UnsuccessfulFrames++;
                    if (m_Tracker.IsTrackedSuccessfully && m_Tracker.TrackedObjects.Any(x => !x.IsLocated))
                        m_PartiallySuccessfulFrames++;

                    SaveEmbeddedOrORCedTimeStamp(frameNo);

                    MeasureObjects();

                    m_PrevMeasuredFrame = m_CurrFrameNo;

                    m_StopWatch.Stop();
                    m_ControlPanel.UpdateProcessedFrames(m_ProcessedFrames, m_UnsuccessfulFrames, m_PartiallySuccessfulFrames, (int)(m_StopWatch.ElapsedMilliseconds / 1000));
                    m_StopWatch.Start();
                }
            }
            else if (m_ViewingLightCurve && m_LightCurveController.LcFile != null)
            {
                var currentSelection = new LCMeasurement[m_LightCurveController.LcFile.Header.ObjectCount];

                if (m_LightCurveController.LcFile.Header.MinFrame <= m_CurrFrameNo &&
                    m_LightCurveController.LcFile.Header.MaxFrame >= m_CurrFrameNo)
                {
                    for (int i = 0; i < m_LightCurveController.LcFile.Header.ObjectCount; i++)
                    {
                        List<LCMeasurement> measurements = m_LightCurveController.Context.AllReadings[i];
                        currentSelection[i] = measurements[(int)(m_CurrFrameNo - m_LightCurveController.LcFile.Header.MinFrame)];
                    }

                    m_LightCurveController.OnNewSelectedMeasurements(currentSelection.ToArray());
                }
            }

            if (m_ControlPanel != null)
                m_ControlPanel.UpdateState();
            if (isLastFrame)
            {
                if (m_Refining)
                {
                    m_ControlPanel.StopRefining();
                    if (TangraConfig.Settings.Tracking.PlaySound)
                        Console.Beep();
                }
                else if (m_Measuring)
                {
                    m_ControlPanel.StopMeasurements(ucLightCurves.StopReason.EndOfFile);

                    if (TangraConfig.Settings.Tracking.PlaySound)
                        Console.Beep();

                    m_ControlPanel.StoppedAtLastFrame();
                }
            }
        }
Example #25
0
 internal PeakPixelResolver(AstroImage image)
 {
     m_Image = image;
 }
        public void NextFrame(int frameNo, MovementType movementType, bool isLastFrame, AstroImage astroImage, int firstFrameInIntegrationPeriod, string fileName)
        {
            m_CurrentFrameNo = frameNo;

            if (m_OperationState == SpectroscopyState.RunningMeasurements)
            {
                if (m_FirstMeasuredFrame == null)
                {
                    m_FirstMeasuredFrame = m_CurrentFrameNo;
                    if (m_VideoController.HasEmbeddedTimeStamps()) m_FirstFrameTimeStamp = m_VideoController.GetCurrentFrameTime();
                    else if (m_VideoController.HasSystemTimeStamps()) m_FirstFrameTimeStamp = m_VideoController.GetCurrentFrameTime();
                    m_FrameBitmapPixels = astroImage.Pixelmap.DisplayBitmapPixels;
                }

                m_Tracker.NextFrame(frameNo, astroImage);
                if (m_Tracker.IsTrackedSuccessfully)
                {
                    TrackedObject trackedStar = m_Tracker.TrackedStar;
                    SelectedStar = trackedStar.Center;

                    m_Reader = new SpectraReader(astroImage, SelectedStarBestAngle, m_SpectroscopyController.SpectraReductionContext.PixelValueCoefficient);

                    Spectra thisFrameSpectra = m_Reader.ReadSpectra(
                        trackedStar.ThisFrameX,
                        trackedStar.ThisFrameY,
                        m_SpectroscopyController.SpectraReductionContext.MeasurementAreaWing,
                        m_SpectroscopyController.SpectraReductionContext.BackgroundAreaWing,
                        m_SpectroscopyController.SpectraReductionContext.BackgroundAreaGap,
                        m_SpectroscopyController.SpectraReductionContext.BackgroundMethod);

                    thisFrameSpectra.ZeroOrderFWHM = trackedStar.PSFFit != null ? (float)trackedStar.PSFFit.FWHM : float.NaN;

                    m_AllFramesSpectra.Add(thisFrameSpectra);
                }

                if (isLastFrame || m_CancelMeasurementsRequested || m_AllFramesSpectra.Count >= m_SpectroscopyController.SpectraReductionContext.FramesToMeasure)
                {
                    m_FramePlayer.Stop();

                    m_MasterSpectra = m_SpectroscopyController.ComputeResult(
                        m_AllFramesSpectra,
                        m_SpectroscopyController.SpectraReductionContext.FrameCombineMethod,
                        m_SpectroscopyController.SpectraReductionContext.UseFineAdjustments,
                        m_SpectroscopyController.SpectraReductionContext.AlignmentAbsorptionLinePos);

                    m_AllFramesSpectra.Clear();

                    m_MasterSpectra.MeasurementInfo = m_SpectroscopyController.GetMeasurementInfo();
                    m_MasterSpectra.MeasurementInfo.FirstMeasuredFrame = m_FirstMeasuredFrame.Value;
                    m_MasterSpectra.MeasurementInfo.LastMeasuredFrame = m_CurrentFrameNo;
                    m_MasterSpectra.MeasurementInfo.FirstFrameTimeStamp = m_FirstFrameTimeStamp;
                    if (m_VideoController.HasEmbeddedTimeStamps())
                        m_MasterSpectra.MeasurementInfo.LastFrameTimeStamp = m_VideoController.GetCurrentFrameTime();
                    else if (m_VideoController.HasSystemTimeStamps())
                        m_MasterSpectra.MeasurementInfo.LastFrameTimeStamp = m_VideoController.GetCurrentFrameTime();

                    FrameStateData frameStatus = m_VideoController.GetCurrentFrameState();
                    m_MasterSpectra.MeasurementInfo.Gain = frameStatus.Gain;
                    m_MasterSpectra.MeasurementInfo.ExposureSeconds = m_SpectroscopyController.SpectraReductionContext.ExposureSeconds;

                    m_MasterSpectra.MeasurementInfo.FrameBitmapPixels = m_FrameBitmapPixels;

                    m_SpectroscopyController.PopulateMasterSpectraObservationDetails(m_MasterSpectra);

                    m_OperationState = SpectroscopyState.DisplayingMeasurements;
                    m_ControlPanel.MeasurementsFinished();
                    DisplaySpectra();
                }

                Application.DoEvents();
            }
        }
Example #27
0
        public static Dictionary<ImagePixel, double> LocateHotPixels(AstroImage image, int averageNTopCandidates)
        {
            var rv = LocateHotPixels(image, s_OriginalSample, s_OriginalSampleMedian);
            if (averageNTopCandidates > 0)
            {
                var allCenters = averageNTopCandidates < s_Candidates.Length
                    ? s_Candidates.Take(averageNTopCandidates)
                    : s_Candidates;

                // Horrible hack !!!
                s_CombinedSample = new uint[7, 7];
                s_NumSamplesCombined = 1;

                foreach (var pixel in allCenters)
                {
                    var model = image.GetPixelsArea(pixel.X, pixel.Y, 7);
                    RegisterHotPixelSample(model, image.Pixelmap.MaxSignalValue);
                }

                rv = LocateHotPixels(image, s_CombinedSample, s_CombinedSampleMedian);
            }

            return rv;
        }
        internal frmAddOrEditSingleTarget(int objectId, ImagePixel center, PSFFit gaussian, LCStateMachine state, VideoController videoController)
        {
            InitializeComponent();

            m_VideoController = videoController;

            m_AutocenteredApertureAvailable = true;

            Text = "Add Object";
            btnAdd.Text = "Add";
            btnDontAdd.Text = "Don't Add";
            btnDelete.Visible = false;
            m_IsEdit = false;

            nudFitMatrixSize.Value = 11;
            nudFitMatrixSize.Maximum = 15;

            m_ObjectId = objectId;
            m_State = state;
            m_AstroImage = m_State.VideoOperation.m_StackedAstroImage;

            ObjectToAdd = new TrackedObjectConfig();

            m_Center = new ImagePixel(center);

            Initialize();

            if (rbOccultedStar.Enabled)
                SelectedObjectType = TrackingType.OccultedStar;
            else
                SelectedObjectType = TrackingType.GuidingStar;

            // Apply filtering to the processing pixels according to the configured default filter value
            int matirxSize = (int)nudFitMatrixSize.Value;

            GetFitInMatrix(gaussian, ref matirxSize);

            nudFitMatrixSize.Maximum = matirxSize;

            if (SelectedObjectType != TrackingType.OccultedStar)
                SetHeightAndType();
        }
        private void InitStarAmplitudeModelling(ModelConfig modelConfig, float accuracy, int bitPix, uint maxSignalValue)
        {
            if (m_MagnitudeToPeakDict != null)
                return;

            m_MagnitudeToPeakDict = new Dictionary<double, int>();
            m_MagnitudeToPeakMags = new List<double>();
            m_MagnitudeToPeakPeaks = new List<int>();

            var mea = new MeasurementsHelper(
                bitPix,
                TangraConfig.BackgroundMethod.BackgroundMedian,
                TangraConfig.Settings.Photometry.SubPixelSquareSize,
                TangraConfig.Settings.Photometry.Saturation.GetSaturationForBpp(bitPix, maxSignalValue));

            float apertureSize = APERTURE;
            float annulusInnerRadius = (GAP + APERTURE) / APERTURE;
            int annulusMinPixels = (int)(Math.PI * (Math.Pow(ANNULUS + GAP + APERTURE, 2) - Math.Pow(GAP + APERTURE, 2)));

            mea.SetCoreProperties(annulusInnerRadius, annulusMinPixels, CorePhotometrySettings.Default.RejectionBackgroundPixelsStdDev, 2 /* TODO: This must be configurable */);

            int peak = (int)(maxSignalValue - (modelConfig.NoiseMean + modelConfig.DarkFrameMean) * modelConfig.Integration);
            int TOTAL_STEPS = 100;
            double step = Math.Log10(peak) / TOTAL_STEPS;
            double zeroMag = double.NaN;
            for (int ii = 0; ii < TOTAL_STEPS; ii++)
            {
                int amplitude = (int)Math.Round(Math.Pow(10, Math.Log10(peak) - ii * step));
                Pixelmap pixmap = new Pixelmap(64, 64, bitPix, new uint[64 * 64], null, null);
                VideoModelUtils.GenerateStar(pixmap, 32, 32, (float)modelConfig.FWHM, amplitude, 0 /* Gaussian */);
                PSFFit fit = new PSFFit(32, 32);
                AstroImage img = new AstroImage(pixmap);
                uint[,] data = img.GetMeasurableAreaPixels(32, 32, 17);
                uint[,] backgroundPixels = img.GetMeasurableAreaPixels(32, 32, 35);

                fit.Fit(data);

                var result = mea.MeasureObject(new ImagePixel(32, 32), data, backgroundPixels, pixmap.BitPixCamera,
                    TangraConfig.PreProcessingFilter.NoFilter,
                    TangraConfig.PhotometryReductionMethod.AperturePhotometry, TangraConfig.PsfQuadrature.NumericalInAperture,
                    TangraConfig.PsfFittingMethod.DirectNonLinearFit,
                    apertureSize, modelConfig.FWHM, (float)modelConfig.FWHM,
                    new FakeIMeasuredObject(fit),
                    null, null,
                    false);

                if (result == NotMeasuredReasons.TrackedSuccessfully && !mea.HasSaturatedPixels)
                {
                    // Add value for fitting
                    double measurement = mea.TotalReading - mea.TotalBackground;
                    if (double.IsNaN(zeroMag))
                        zeroMag = modelConfig.BrighestUnsaturatedStarMag + 2.5 * Math.Log10(measurement);
                    double magnitude = -2.5 * Math.Log10(measurement) + zeroMag;

                    m_MagnitudeToPeakDict[magnitude] = amplitude;
                    m_MagnitudeToPeakMags.Add(magnitude);
                    m_MagnitudeToPeakPeaks.Add(amplitude);
                }
            }
        }
        public void NextFrame(int frameNo, MovementType movementType, bool isLastFrame, AstroImage astroImage, int firstFrameInIntegrationPeriod, string fileName)
        {
            m_ControlPanel.NextFrame(frameNo, m_Status);

            if (m_Status == ConvertVideoToFitsState.Converting)
            {
                var timestamp = DateTime.MinValue;
                float exposureSeconds = 0;

                if (m_VideoController.HasTimestampOCR())
                {
                    m_OCRedTimeStamp = m_VideoController.OCRTimestamp();

                    timestamp = m_OCRedTimeStamp;
                    if (m_PrevOCRedTimeStamp.HasValue)
                        exposureSeconds = (float)new TimeSpan(timestamp.Ticks - m_PrevOCRedTimeStamp.Value.Ticks).TotalSeconds;
                    m_PrevOCRedTimeStamp = timestamp;
                }
                else
                {
                    if (m_VideoController.HasEmbeddedTimeStamps())
                    {
                        timestamp = astroImage.Pixelmap.FrameState.CentralExposureTime;
                        exposureSeconds = astroImage.Pixelmap.FrameState.ExposureInMilliseconds / 1000.0f;
                    }
                    else
                    {
                        timestamp = m_StartFrameTime.AddTicks((long)(frameNo - m_StartTimeFrame) * (m_EndFrameTime.Ticks - m_StartFrameTime.Ticks) / (m_EndTimeFrame - m_StartTimeFrame));
                        exposureSeconds = (float)(new TimeSpan((m_EndFrameTime.Ticks - m_StartFrameTime.Ticks) / (m_EndTimeFrame - m_StartTimeFrame)).TotalSeconds);
                    }
                }

                m_ConvertVideoToFitsController.ProcessFrame(frameNo, astroImage, timestamp, exposureSeconds);

                if (isLastFrame || m_LastFrame == frameNo)
                {
                    m_ConvertVideoToFitsController.FinishExport();
                    m_ControlPanel.ExportFinished();
                    m_Status = ConvertVideoToFitsState.Finished;
                    m_VideoController.ShowMessageBox("Export completed.", "Tangra", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                if (m_LastFrame == frameNo)
                    m_VideoController.StopVideo();
            }
        }