public void DetectConnected()
        {
            var classificator = new SkyCloudClassification(processingImage, defaultProperties);

            classificator.Classify();
            DenseMatrix        dmSkyIndexDataBinary  = classificator.dmSkyIndexDataBinary();
            Image <Gray, Byte> imgSkyIndexDataBinary = ImageProcessing.grayscaleImageFromDenseMatrixWithFixedValuesBounds(dmSkyIndexDataBinary, 0.0d, 1.0d, true);

            imgSkyIndexDataBinary = imgSkyIndexDataBinary.Mul(classificator.maskImage);
            Image <Bgr, Byte> previewImage = imgSkyIndexDataBinary.CopyBlank().Convert <Bgr, Byte>();


            // Contour<Point> contoursDetected = imgSkyIndexDataBinary.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_LIST);

            #region // EmguCV 3.0
            //VectorOfVectorOfPoint contoursDetected = new VectorOfVectorOfPoint();
            //CvInvoke.FindContours(imgSkyIndexDataBinary, contoursDetected, null, Emgu.CV.CvEnum.RetrType.List,
            //    Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            //contoursArray = new List<VectorOfPoint>();
            //int count = contoursDetected.Size;
            //var colorGen = new RandomPastelColorGenerator();
            //for (int i = 0; i < count; i++)
            //{
            //    Color currentColor = colorGen.GetNext();
            //    var currentColorBgr = new Bgr(currentColor.B, currentColor.G, currentColor.R);
            //    using (VectorOfPoint currContour = contoursDetected[i])
            //    {
            //        contoursArray.Add(currContour);
            //        previewImage.Draw(currContour.ToArray(), currentColorBgr, -1); //.Draw(currContour, currentColorBgr, -1);
            //    }
            //}
            #endregion // EmguCV 3.0


            List <Contour <Point> >    contoursDetected = imgSkyIndexDataBinary.DetectContours();
            RandomPastelColorGenerator colorGen         = new RandomPastelColorGenerator();
            foreach (Contour <Point> currContour in contoursDetected)
            {
                Color currentColor    = colorGen.GetNext();
                Bgr   currentColorBgr = new Bgr(currentColor.B, currentColor.G, currentColor.R);
                previewImage.Draw(currContour, currentColorBgr, -1);
            }


            ThreadSafeOperations.SetTextTB(tbLog, "Количество выделенных объектов: " + contoursArray.Count + Environment.NewLine, true);


            //ShowImageForm ImgShow = new ShowImageForm(localPreviewBitmap, ParentForm, this);
            var imgShow = new SimpleShowImageForm(previewImage);
            imgShow.Show();
        }
Esempio 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);
        }