private void ProcessImage(ImageStatsCollectingData srcData)
        {
            Interlocked.Increment(ref totalFilesProcessed);
            int perc = Convert.ToInt32(100.0d * (double)totalFilesProcessed / (double)totalFilesCountToProcess);

            Console.WriteLine(DateTime.Now.ToString("s") + " : " + perc + "% : started processing file " + Environment.NewLine + srcData.filename);

            Dictionary <string, object> optionalParameters = new Dictionary <string, object>();

            optionalParameters.Add("logFileName", errorLogFilename);


            // найти и записать данные GPS
            GPSdata currimageGPS = ServiceTools.FindProperGPSdataForImage(srcData.filename, null, defaultProperties,
                                                                          ref NVdataFilesAlreadyReadDateTimeSpans, ref NVdataFilesAlreadyReadData);

            if (currimageGPS != null)
            {
                ServiceTools.WriteObjectToXML(currimageGPS,
                                              ConventionalTransitions.ConcurrentGPSdataFileName(srcData.filename, strConcurrentGPSdataXMLfilesPath));
            }


            // найти и записать данные SDC и Cloud Cover
            DateTime curDateTime = GetImageDateTime(srcData.filename);

            if (!lMissionObservedData.Any())
            {
                return;
            }
            lMissionObservedData.Sort((obsRecord1, obsRecord2) =>
            {
                double dev1 = Math.Abs((obsRecord1.dateTime - curDateTime).TotalMilliseconds);
                double dev2 = Math.Abs((obsRecord2.dateTime - curDateTime).TotalMilliseconds);
                return((dev1 >= dev2) ? (1) : (-1));
            });
            MissionsObservedData closestObservedDatum = lMissionObservedData[0];

            if ((closestObservedDatum.dateTime - curDateTime).TotalSeconds > 600)
            {
                return;
            }



            SunDiskConditionData currImageSDC = new SunDiskConditionData()
            {
                filename         = srcData.filename,
                sunDiskCondition = closestObservedDatum.SDC
            };

            ServiceTools.WriteObjectToXML(currImageSDC,
                                          ConventionalTransitions.SunDiskConditionFileName(srcData.filename, SunDiskConditionXMLdataFilesDirectory));



            // find grixyrgbStatsXMLfile
            SkyImageIndexesStatsData currImageStatsData = null;
            string currImageStatsDataXMLfile            = "";

            if (Directory.Exists(imageYRGBstatsXMLdataFilesDirectory))
            {
                List <string> foundXMLfiles = Directory.EnumerateFiles(imageYRGBstatsXMLdataFilesDirectory,
                                                                       ConventionalTransitions.ImageGrIxYRGBstatsDataFileName(srcData.filename, "", false),
                                                                       SearchOption.AllDirectories).ToList();
                if (foundXMLfiles.Any())
                {
                    // возьмем первый попавшийся
                    currImageStatsDataXMLfile = foundXMLfiles[0];
                    currImageStatsData        =
                        (SkyImageIndexesStatsData)
                        ServiceTools.ReadObjectFromXML(currImageStatsDataXMLfile, typeof(SkyImageIndexesStatsData));
                }
            }



            SkyImagesDataWith_Concurrent_Stats_CloudCover_SDC currImageData = new SkyImagesDataWith_Concurrent_Stats_CloudCover_SDC
                                                                                  ()
            {
                skyImageFullFileName   = srcData.filename,
                skyImageFileName       = Path.GetFileName(srcData.filename),
                currImageDateTime      = curDateTime,
                observedCloudCoverData = new ObservedClCoverData()
                {
                    dt = closestObservedDatum.dateTime,
                    CloudCoverTotal = closestObservedDatum.CloudCoverTotal,
                    CloudCoverLower = closestObservedDatum.CloudCoverLower
                },
                concurrentDataXMLfile = "",
                concurrentData        = new ConcurrentData()
                {
                    filename       = "",
                    datetimeUTC    = currimageGPS.DateTimeUTC,
                    GPSdata        = "",
                    GPSLat         = currimageGPS.Lat,
                    GPSLon         = currimageGPS.Lon,
                    GPSDateTimeUTC = currimageGPS.DateTimeUTC,
                    PressurePa     = closestObservedDatum.pressure,
                    gps            = currimageGPS
                },
                grixyrgbStatsXMLfile = currImageStatsDataXMLfile,
                grixyrgbStats        = currImageStatsData,
                SDCvalue             = closestObservedDatum.SDC
            };

            ServiceTools.WriteObjectToXML(currImageData,
                                          ConventionalTransitions.SkyImagesDataWithConcurrentStatsCloudCoverAndSDC_FileName(srcData.filename,
                                                                                                                            strSkyImagesDataWithConcurrentStatsCloudCoverAndSDCDirectory));
        }
Ejemplo n.º 2
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);
        }