Example #1
0
        private AngleSunDeviationCalcResult CalculateDevDataForImage(FileInfo finfo, Dictionary <string, object> defaultProperties, LogWindow currImageLogWindow, bool showOnlyErrors = false)
        {
            FileInfo currFileInfo = finfo;
            Dictionary <string, object> defaultProps = defaultProperties;


            AngleSunDeviationCalcResult retRes = new AngleSunDeviationCalcResult()
            {
                fileName = currFileInfo.FullName,
            };

            GPSdata gps = ServiceTools.FindProperGPSdataForImage(currFileInfo.FullName, theLogWindow, defaultProperties,
                                                                 ref NVdataFilesAlreadyReadDateTimeSpans, ref NVdataFilesAlreadyReadData);

            if (gps == null)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow, "Couldn`t find GPS data for this image.");
                retRes.calculationSucceeded = false;
                retRes.resultMessage        = "Couldn`t find GPS data for this image.";
                return(retRes);
            }

            #region // obsolete
            //// определяем дату-время файла
            //DateTime curDateTime = DateTime.UtcNow;

            //Image anImage = Image.FromFile(currFileInfo.FullName);
            //ImageInfo newIInfo = new ImageInfo(anImage);
            //int minute = 0;
            //String dateTime = (String)newIInfo.getValueByKey("ExifDTOrig");
            //if (dateTime == null)
            //{
            //    //попробуем вытащить из имени файла
            //    string strDateTime = currFileInfo.Name;
            //    strDateTime = strDateTime.Substring(4, 19);
            //    dateTime = strDateTime;
            //}

            //try
            //{
            //    curDateTime = CommonTools.DateTimeOfString(dateTime);
            //}
            //catch (Exception)
            //{
            //    retRes.calculationSucceeded = false;
            //    retRes.resultMessage = "couldn`t get date/time for file: " + Environment.NewLine + currFileInfo.Name;
            //    return retRes;
            //}
            //curDateTime = DateTime.SpecifyKind(curDateTime, DateTimeKind.Utc);

            //GPSdata neededGPSdata = new GPSdata();
            //string currPath = currFileInfo.DirectoryName;


            //string navFilesPath = defaultProps["IoffeMeteoNavFilesDirectory"] as string;
            //List<IoffeVesselDualNavDataConverted> lAllNavData = new List<IoffeVesselDualNavDataConverted>();

            //string[] sNavFilenames = Directory.GetFiles(navFilesPath, "*.nv2", SearchOption.AllDirectories);
            //if (!sNavFilenames.Any())
            //{
            //    retRes.calculationSucceeded = false;
            //    retRes.resultMessage = "Не найдено файлов данных навигации в директории " + navFilesPath;
            //    return retRes;
            //}
            //else
            //{
            //    foreach (string navFilename in sNavFilenames)
            //    {
            //        Tuple<DateTime, DateTime> timeSpan =
            //            IoffeVesselNavDataReader.GetNavFileDateTimeMargins(navFilename);
            //        if (timeSpan == null)
            //        {
            //            continue;
            //        }

            //        if ((curDateTime < timeSpan.Item1) || (curDateTime > timeSpan.Item2))
            //        {
            //            continue;
            //        }

            //        List<IoffeVesselDualNavDataConverted> dataHasBeenRead = IoffeVesselNavDataReader.ReadNavFile(navFilename);
            //        if (dataHasBeenRead == null)
            //        {
            //            continue;
            //        }
            //        Application.DoEvents();
            //        lAllNavData.AddRange(dataHasBeenRead);
            //    }
            //}

            //lAllNavData.Sort((gpsRecord1, gpsRecord2) =>
            //{
            //    double dev1 = Math.Abs((gpsRecord1.gps.dateTimeUTC - curDateTime).TotalMilliseconds);
            //    double dev2 = Math.Abs((gpsRecord2.gps.dateTimeUTC - curDateTime).TotalMilliseconds);
            //    return (dev1 >= dev2) ? (1) : (-1);
            //});
            //neededGPSdata = lAllNavData[0].gps;
            #endregion // obsolete

            retRes.gpsData = gps;


            #region obsolete
            //double lat = gps.LatDec;
            //double lon = gps.LonDec;


            //SPA spaCalc = new SPA(curDateTime.Year, curDateTime.Month, curDateTime.Day, curDateTime.Hour,
            //    curDateTime.Minute, curDateTime.Second, (float)lon, (float)lat,
            //    (float)SPAConst.DeltaT(curDateTime));
            //int res = spaCalc.spa_calculate();
            //AzimuthZenithAngle sunPositionSPAext = new AzimuthZenithAngle(spaCalc.spa.azimuth,
            //    spaCalc.spa.zenith);
            #endregion obsolete


            AzimuthZenithAngle sunPositionSPAext = gps.SunZenithAzimuth();

            if (!showOnlyErrors)
            {
                currImageLogWindow = ServiceTools.LogAText(currImageLogWindow,
                                                           "SPA ext sun position for " + gps.dateTimeUTC.ToString("s") + ": " + sunPositionSPAext);
            }

            retRes.sunSPAcomputedPosition = sunPositionSPAext;



            Image <Bgr, Byte> img2process = new Image <Bgr, byte>(currFileInfo.FullName);
            img2process = ImageProcessing.ImageResizer(img2process, Convert.ToInt32(defaultProps["DefaultMaxImageSize"]));
            Image <Bgr, Byte> LocalProcessingImage = ImageProcessing.SquareImageDimensions(img2process);

            RoundData sunRoundData = RoundData.nullRoundData();

            //посмотрим, нет ли уже имеющихся данных о положении и размере солнечного диска на изображении
            string sunDiskInfoFileName = ConventionalTransitions.SunDiskInfoFileName(currFileInfo.FullName);
            //string sunDiskInfoFileName = currFileInfo.DirectoryName + "\\" +
            //                             Path.GetFileNameWithoutExtension(currFileInfo.FullName) + "-SunDiskInfo.xml";

            RoundData existingRoundData             = RoundData.nullRoundData();
            Size      imgSizeUnderExistingRoundData = LocalProcessingImage.Bitmap.Size;
            object    existingRoundDataObj          = ServiceTools.ReadObjectFromXML(sunDiskInfoFileName, typeof(RoundDataWithUnderlyingImgSize));

            if (existingRoundDataObj != null)
            {
                existingRoundData             = ((RoundDataWithUnderlyingImgSize)existingRoundDataObj).circle;
                imgSizeUnderExistingRoundData = ((RoundDataWithUnderlyingImgSize)existingRoundDataObj).imgSize;
            }

            double currScale = (double)LocalProcessingImage.Width / (double)imgSizeUnderExistingRoundData.Width;
            if (currScale != 1.0d)
            {
                existingRoundData.DCenterX *= currScale;
                existingRoundData.DCenterY *= currScale;
                existingRoundData.DRadius  *= currScale;
            }
            if (!existingRoundData.IsNull)
            {
                sunRoundData = existingRoundData;
            }

            ImageProcessing imgP = new ImageProcessing(LocalProcessingImage, true);

            if (sunRoundData.IsNull)
            {
                SkyCloudClassification classificator = new SkyCloudClassification(img2process, defaultProperties);
                classificator.verbosityLevel             = 0;
                classificator.ParentForm                 = ParentForm;
                classificator.theLogWindow               = currImageLogWindow;
                classificator.ClassificationMethod       = ClassificationMethods.GrIx;
                classificator.isCalculatingUsingBgWorker = false;
                // classificator.SelfWorker = currBGWsender as BackgroundWorker;
                classificator.defaultOutputDataDirectory = (string)defaultProps["DefaultDataFilesLocation"];
                classificator.theStdDevMarginValueDefiningSkyCloudSeparation =
                    Convert.ToDouble(defaultProps["GrIxDefaultSkyCloudMarginWithoutSun"]);
                classificator.sourceImageFileName = currFileInfo.FullName;

                retRes.imageEdgesDetected = new RoundDataWithUnderlyingImgSize()
                {
                    circle  = imgP.imageRD,
                    imgSize = LocalProcessingImage.Size,
                };
                DenseMatrix dmProcessingData = (DenseMatrix)imgP.eval("grix").Clone();
                try
                {
                    sunRoundData = classificator.DetectSunWithSerieOfArcs(imgP, dmProcessingData);
                    if (!sunRoundData.IsNull)
                    {
                        RoundDataWithUnderlyingImgSize infoToSave = new RoundDataWithUnderlyingImgSize()
                        {
                            circle  = sunRoundData,
                            imgSize = LocalProcessingImage.Size,
                        };
                        ServiceTools.WriteObjectToXML(infoToSave, sunDiskInfoFileName);
                    }
                }
                catch (Exception ex)
                {
                    retRes.calculationSucceeded = false;
                    retRes.resultMessage        = ex.Message;
                    return(retRes);
                }
                ServiceTools.FlushMemory();
            }



            if (sunRoundData.IsNull)
            {
                throw new Exception(finfo.Name + ": couldn`t detect sun position");
            }
            else
            {
                retRes.sunDiskDetectedPosition = new RoundDataWithUnderlyingImgSize()
                {
                    circle  = sunRoundData,
                    imgSize = LocalProcessingImage.Size,
                };
            }



            RoundData imageDetectedRound = imgP.imageRD.Copy();
            retRes.imageEdgesDetected = new RoundDataWithUnderlyingImgSize()
            {
                circle  = imageDetectedRound,
                imgSize = LocalProcessingImage.Size,
            };

            try
            {
                double dev = retRes.computedAzimuthDeviation;
                retRes.calculationSucceeded = true;
            }
            catch (Exception ex)
            {
                retRes.calculationSucceeded = false;
                retRes.resultMessage        = ex.Message;
                return(retRes);
            }

            return(retRes);
        }
Example #2
0
        void currBgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker            selfWorker        = sender as BackgroundWorker;
            FileInfo                    finfo             = ((object[])e.Argument)[0] as FileInfo;
            Dictionary <string, object> defaultProperties = ((object[])e.Argument)[1] as Dictionary <string, object>;
            //int currentBgwID = (int) ((object[]) e.Argument)[2];
            LogWindow currImageLogWindow = null;
            bool      showOnlyErrors     = false;

            string sunDiskInfoFileName = finfo.DirectoryName + "\\" +
                                         Path.GetFileNameWithoutExtension(finfo.FullName) + "-SunDiskInfo.xml";

            if (File.Exists(sunDiskInfoFileName))
            {
                showOnlyErrors = true;
            }

            try
            {
                if (finfo == null)
                {
                    e.Result = false;
                    return;
                }

                if (!showOnlyErrors)
                {
                    currImageLogWindow = ServiceTools.LogAText(currImageLogWindow, Environment.NewLine + "starting: " + finfo.Name);
                    currImageLogWindow = ServiceTools.LogAText(currImageLogWindow, "start processing image " + finfo.Name);
                }


                AngleSunDeviationCalcResult devCalcResDatum = CalculateDevDataForImage(finfo, defaultProperties, currImageLogWindow, showOnlyErrors);


                if (devCalcResDatum.calculationSucceeded)
                {
                    cbAnglesSunDeviationCalcResults.Add(devCalcResDatum);
                }


                if (!showOnlyErrors)
                {
                    currImageLogWindow = ServiceTools.LogAText(currImageLogWindow,
                                                               Environment.NewLine + "finished: " + Path.GetFileName(devCalcResDatum.fileName) +
                                                               " with result: " + devCalcResDatum.calculationSucceeded + Environment.NewLine +
                                                               devCalcResDatum.resultMessage);
                }


                if (currImageLogWindow != null)
                {
                    currImageLogWindow.Close();
                }
            }
            catch (Exception ex)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     Environment.NewLine + "ERROR. There exceptions has been thrown: " + Environment.NewLine + ex.Message);

                string strDirForFailedImages = Path.GetDirectoryName(finfo.FullName);
                strDirForFailedImages += (strDirForFailedImages.Last() == '\\') ? ("") : ("\\") + "failed-detections\\";
                try
                {
                    if (ServiceTools.CheckIfDirectoryExists(strDirForFailedImages))
                    {
                        File.Move(finfo.FullName, strDirForFailedImages + finfo.Name);
                    }
                }
                catch (Exception ex1)
                {
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         Environment.NewLine + "ERROR. There exceptions has been thrown: " + Environment.NewLine +
                                                         ex1.Message);
                }


                if (currImageLogWindow != null)
                {
                    currImageLogWindow.Close();
                }
            }


            e.Result = new object[] { true };
        }