Ejemplo n.º 1
0
        public void OnAddLocalImage()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Filter = "Image Files|*.BMP;*.JPG;*.JPEG,*.PNG";
            fileDialog.ShowDialog();
            if (fileDialog.CheckFileExists && fileDialog.FileName != "")
            {
                var result = MessageBox.Show("Чи це кіт?", "Це кіт?", MessageBoxButton.YesNo, MessageBoxImage.Question);
                try
                {
                    byte[] selectImageBytes;
                    using (var selectFileStream = new FileStream(fileDialog.FileName, FileMode.OpenOrCreate))
                    {
                        selectImageBytes = new byte[selectFileStream.Length];
                        selectFileStream.Read(selectImageBytes, 0, (int)selectFileStream.Length);
                    }
                    var localImage = LocalImage.GenerateNewLocalFileFromImageTypeAndData(result == MessageBoxResult.Yes ? ImageType.CAT : ImageType.NOT_CAT, selectImageBytes).Result;
                    LocalImageCollection.Insert(0, localImage);
                }
                catch
                {
                    MessageBox.Show("Неможливо відкрити файл - " + fileDialog.FileName, "Неможливо відкрити файл!");
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// For the current image that we're checking, check all other files
        /// in that directory (or also all subdirectories, if requested) for
        /// duplication.
        /// </summary>
        /// <param name="inDirectory"></param>
        /// <param name="localImage"></param>
        /// <param name="visited"></param>
        /// <returns></returns>
        Task <DuplicateImage[]> VisitOthers(
            LocalImage[] inDirectory,
            LocalImage localImage,
            List <string> visited) =>
        Task.Run(async() =>
        {
            var duplicates = new List <DuplicateImage>();
            for (var index = 0; index < inDirectory.Length; index++)
            {
                // If we've already processed the image at some point,
                // skip it.
                if (inDirectory[index].Name == localImage.Name)
                {
                    continue;
                }

                var isDuplicate = await UpdateDuplicationCollection(
                    localImage,
                    inDirectory[index],
                    duplicates);

                // Mark found duplicates as already visited. We don't
                // want to bother re-processing images.
                if (isDuplicate)
                {
                    visited.Add(inDirectory[index].Name);
                }
            }

            return(duplicates.ToArray());
        });
Ejemplo n.º 3
0
        protected override async Task <Option <DuplicateImage> > DirectComparison(LocalImage source, LocalImage target)
        {
            var percentageEquivalent = await differenceCalculator.CalculatePercentage(
                new Bitmap(source.FilePath),
                new Bitmap(target.FilePath));

            return(new Some <DuplicateImage>(new DuplicateImage(target, percentageEquivalent)));
        }
Ejemplo n.º 4
0
        public async void GetImageName_returns_correct_name()
        {
            var image = new LocalImage {
                ImagePath = "C:\\example\\test.jpg"
            };

            Assert.Equal("test.jpg", await image.GetImageName());
        }
            public ModelManagerBase()
            {
                lstCat = new SelectedPwgAlbumList();
                lstAlbumLocaux = new LocalAlbumList();
                isConnected = false;

                AlbumEdited = new LocalAlbum();
                ImageEdited = new LocalImage();
                UploadOption = new PwgUploadOption();

                LstConfidentLevel = Com.Piwigo.Lib.DTO.Helper.PwgEnumHelper<PwgConfidentLevelEnum>.buildChoiceList();
            }
        internal void uploadImage(LocalImage aImg)
        {
            FileInfo fi = new FileInfo(aImg.LocalFile);

            List<PwgTag> lstTag = new List<PwgTag>();
            if (aImg.LstTags != null)
            {
                lstTag.AddRange(aImg.LstTags);
            }

            PwgServiceProvider.Instance.PwgImagesService.addImageByMultiPartForm(fi, null, aImg.UpperCatId, aImg.Name, aImg.Author, aImg.AuthorComment, aImg.ConfidentialLevel, lstTag);
        }
Ejemplo n.º 7
0
        public void OnRefreshLocalImagesFromDirectory()
        {
            loadingLocalFilesTaskCancellationToken = new CancellationTokenSource();
            loadingLocalFilesTaskCancellationToken.Token.Register(() =>
            {
            });
            this.LoadingFilesFromDirectory = false;
            Task task = new Task(() =>
            {
                try
                {
                    var standardMessage            = "Reading from directory. Please Wait...";
                    this.LoadingFilesFromDirectory = true;
                    this.StatusMessage             = standardMessage;
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        LocalImageCollection.Clear();
                    });
                    var localImages = LocalImage.ReadAllLocalImagesFromDirectory((progress) => {
                        this.StatusMessage = standardMessage + " Progress: " + progress + "%";
                    }).OrderBy(r => Path.GetFileName(r.LocalPath));

                    if (localImages.Count() == 0)
                    {
                        MessageBox.Show("No Images in the directories", "No Images", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }

                    App.Current.Dispatcher.Invoke(() =>
                    {
                        foreach (var localImage in localImages)
                        {
                            LocalImageCollection.Add(localImage);
                        }
                    });
                    this.LoadingFilesFromDirectory = false;
                    this.StatusMessage             = "Ready";
                }
                catch (LocalImageFileReadException exception)
                {
                    MessageBox.Show("Curropt File Name: " + exception.FilePath, "File Curropt, Delete It");
                    this.StatusMessage             = "Delete: " + exception.FilePath;
                    this.LoadingFilesFromDirectory = false;
                }
            }, loadingLocalFilesTaskCancellationToken.Token);

            task.Start();
            task.ContinueWith((t) =>
            {
                this.StatusMessage             = "Ready";
                this.LoadingFilesFromDirectory = false;
            });
        }
Ejemplo n.º 8
0
        public void OnRefreshLocalImagesFromDirectory()
        {
            loadingLocalFilesTaskCancellationToken = new CancellationTokenSource();
            loadingLocalFilesTaskCancellationToken.Token.Register(() =>
            {
            });
            this.LoadingFilesFromDirectory = false;
            Task task = new Task(() =>
            {
                try
                {
                    var standardMessage            = "Зчитування з папки. Будь ласка, зачекайте...";
                    this.LoadingFilesFromDirectory = true;
                    this.StatusMessage             = standardMessage;
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        LocalImageCollection.Clear();
                    });
                    var localImages = LocalImage.ReadAllLocalImagesFromDirectory((progress) => {
                        this.StatusMessage = standardMessage + " Прогрес - " + progress.ToString("0") + "%";
                    }).OrderBy(r => Path.GetFileName(r.LocalPath));

                    if (localImages.Count() == 0)
                    {
                        MessageBox.Show("Немає зображень у папках", "Немає зображень", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }

                    App.Current.Dispatcher.Invoke(() =>
                    {
                        foreach (var localImage in localImages)
                        {
                            LocalImageCollection.Add(localImage);
                        }
                    });
                    this.LoadingFilesFromDirectory = false;
                    this.StatusMessage             = "Готово";
                }
                catch (LocalImageFileReadException exception)
                {
                    MessageBox.Show("Пошкоджене ім'я файлу - " + exception.FilePath, "Файл пошкоджено, видаліть його!");
                    this.StatusMessage             = "Delete: " + exception.FilePath;
                    this.LoadingFilesFromDirectory = false;
                }
            }, loadingLocalFilesTaskCancellationToken.Token);

            task.Start();
            task.ContinueWith((t) =>
            {
                this.StatusMessage             = "Готово";
                this.LoadingFilesFromDirectory = false;
            });
        }
Ejemplo n.º 9
0
        public void OnConvertRemoteImagesToLocal()
        {
            if (RemoteImageCollection.Count == 0)
            {
                MessageBox.Show("Немає зображень у віддаленому списку!", "Додайте зображення з CSV файлу");
                return;
            }

            foreach (var remoteImage in RemoteImageCollection)
            {
                remoteImage.Uploaded = false;
            }
            this.GeneratingLocalImagesFromRemote = true;
            var standardStatusMessage = "Перетворення Urls в локальні зображення. Будь ласка, зачекайте... ";

            this.StatusMessage = standardStatusMessage;
            var  counter = 0;
            Task task    = new Task(() =>
            {
                Parallel.ForEach(RemoteImageCollection, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 5
                }, (remoteImage) => {
                    remoteImage.UploadInProgress = true;
                    LocalImage localImage;
                    try
                    {
                        localImage = LocalImage.GenerateLocalImageFromRemote(remoteImage).Result;
                    }
                    catch
                    {
                        remoteImage.Failed = true;
                        return;
                    }

                    App.Current.Dispatcher.Invoke(() =>
                    {
                        LocalImageCollection.Insert(0, localImage);
                        remoteImage.Uploaded = true;
                    });
                    remoteImage.UploadInProgress = false;
                    counter++;
                    this.StatusMessage = (standardStatusMessage + (((double)counter / (double)RemoteImageCollection.Count) * 100).ToString("F2") + "%");
                });
            });

            task.Start();
            task.ContinueWith(new Action <Task>((task1) => {
                this.GeneratingLocalImagesFromRemote = false;
                this.StatusMessage = "Готово";
            }));
        }
Ejemplo n.º 10
0
        public void OnConvertRemoteImagesToLocal()
        {
            if (RemoteImageCollection.Count == 0)
            {
                MessageBox.Show("No Images in Remote Image List to Download!", "Add Remote Images by CSV File");
                return;
            }

            foreach (var remoteImage in RemoteImageCollection)
            {
                remoteImage.Uploaded = false;
            }
            this.GeneratingLocalImagesFromRemote = true;
            var standardStatusMessage = "Converting Remote Urls into LocalImages. Please Wait... ";

            this.StatusMessage = standardStatusMessage;
            var  counter = 0;
            Task task    = new Task(() =>
            {
                Parallel.ForEach(RemoteImageCollection, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 5
                }, (remoteImage) => {
                    remoteImage.UploadInProgress = true;
                    LocalImage localImage;
                    try
                    {
                        localImage = LocalImage.GenerateLocalImageFromRemote(remoteImage).Result;
                    }
                    catch
                    {
                        remoteImage.Failed = true;
                        return;
                    }

                    App.Current.Dispatcher.Invoke(() =>
                    {
                        LocalImageCollection.Insert(0, localImage);
                        remoteImage.Uploaded = true;
                    });
                    remoteImage.UploadInProgress = false;
                    counter++;
                    this.StatusMessage = (standardStatusMessage + (((double)counter / (double)RemoteImageCollection.Count) * 100).ToString("F2") + "%");
                });
            });

            task.Start();
            task.ContinueWith(new Action <Task>((task1) => {
                this.GeneratingLocalImagesFromRemote = false;
                this.StatusMessage = "Ready";
            }));
        }
        public void OnLoadImageFormFilePath(string filePath)
        {
            detectImageTaskCancellationToken = new CancellationTokenSource();
            detectImageTaskCancellationToken.Token.Register(() =>
            {
            });
            var testingProgressMessage = "Розпізнавання в прогресі. Будь ласка, зачекайте... ";

            this.DetectionInProgress = true;
            StatusMessageUpdater(testingProgressMessage);
            Task task = new Task(() =>
            {
                Image <Bgr, Byte> image = new Image <Bgr, byte>(filePath);
                this.OriginalImage      = image.Resize(1000, 1000, Inter.Cubic, false);
                var processedImage      = LocalImage.ConvertOriginalImageToGrayScaleAndProcess(this.OriginalImage);
                this.ProcessedImage     = processedImage;

                (ImageType imageType, List <System.Drawing.Rectangle> rectangles) = Detector.DetectCatInImageFile(NeuralNetwork, this.OriginalImage, this.ProcessedImage, (progress) => {
                    StatusMessageUpdater(testingProgressMessage + " Прогрес - " + progress.ToString("0") + "%");
                });

                if (imageType == ImageType.CAT)
                {
                    var rectanglesImage = new Image <Bgr, Byte>(OriginalImage.Width, OriginalImage.Height, new Bgr(0, 0, 0));
                    foreach (var rectangle in rectangles)
                    {
                        rectanglesImage.Draw(rectangle, new Bgr(150, 0, 0), 2);
                    }
                    OriginalImage     = OriginalImage.AddWeighted(rectanglesImage, 1, 1, 0);
                    var mainRectangle = AnchorBox.GetBoundingReactange(rectangles);
                    OriginalImage.Draw(mainRectangle, new Bgr(0, 200, 0), 5);
                    OriginalImage.Draw("Cat", new System.Drawing.Point(30, 120), FontFace.HersheyPlain, 8f, new Bgr(0, 200, 0), 10);
                }
                else
                {
                    OriginalImage.Draw("No cat", new System.Drawing.Point(30, 120), FontFace.HersheyPlain, 8f, new Bgr(0, 0, 255), 10);
                }

                var temp               = this.OriginalImage;
                this.OriginalImage     = null;
                this.OriginalImage     = temp;
                this.OriginalImage.ROI = System.Drawing.Rectangle.Empty;
            });

            task.Start();
            task.ContinueWith((t) => {
                this.DetectionInProgress = false;
                StatusMessageUpdater("Готово");
            });
        }
Ejemplo n.º 12
0
        protected virtual async Task <Option <DuplicateImage> > DirectComparison(LocalImage source, LocalImage target)
        {
            // First, we check for 100% equality. This is much faster when
            // C# gets to do it's own thing. Doing it this way also means
            // we don't have to got into generating the equality percent if
            // we don't need to. If they aren't fully equal, we move on to
            // hash comparison, using the Bias Factor in our options.
            if (source.Hash == target.Hash)
            {
                return(new Some <DuplicateImage>(new DuplicateImage(target, 1.0)));
            }

            return(new None <DuplicateImage>());
        }
Ejemplo n.º 13
0
        async Task <DuplicateImage[]> CompareToOthers(LocalImage source, LocalImage[] targets)
        {
            var duplicates = new List <DuplicateImage>();

            for (var index = 0; index < targets.Length; index++)
            {
                await UpdateDuplicationCollection(
                    source,
                    targets[index],
                    duplicates);
            }

            return(duplicates.ToArray());
        }
Ejemplo n.º 14
0
        public (double[][], double[][]) GetBatchDataFromImages(IPagedList <LocalImage> localImages)
        {
            var numberOfImages = localImages.Count;

            double[][] batchInputs  = new double[numberOfImages][];
            double[][] batchOutputs = new double[numberOfImages][];
            foreach (int i in Enumerable.Range(0, numberOfImages))
            {
                var currentLocalImage = localImages[i];
                (double[] normalizedImageData, ImageType imageType) = LocalImage.GetImageInformationForNeuralNetwork(currentLocalImage);
                batchInputs[i]  = normalizedImageData;
                batchOutputs[i] = new double[] { currentLocalImage.ImageType == ImageType.CAT ? 1 : 0, currentLocalImage.ImageType == ImageType.CAT ? 0 : 1 };
            }
            return(batchInputs, batchOutputs);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// If the images have the same hash, add them to the duplicate collection.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <param name="duplicateImages"></param>
        /// <returns>`true` if the item was added, and `false` if not.</returns>
        protected async Task <bool> UpdateDuplicationCollection(
            LocalImage source,
            LocalImage target,
            List <DuplicateImage> duplicateImages)
        {
            var duplicate = await DirectComparison(source, target);

            if (duplicate.IsNone)
            {
                return(false);
            }

            duplicateImages.Add(duplicate.Value);

            return(true);
        }
Ejemplo n.º 16
0
        protected override async Task <Option <DuplicateImage> > DirectComparison(LocalImage source, LocalImage target)
        {
            var directResult = await base.DirectComparison(source, target);

            if (directResult.IsSome)
            {
                return(directResult);
            }

            var percentage = await differenceCalculator.CalculatePercentage(
                source.Hash,
                target.Hash);

            if (percentage >= comparisonOptions.BiasPercent)
            {
                return(new Some <DuplicateImage>(new DuplicateImage(target, percentage)));
            }

            return(new None <DuplicateImage>());
        }
 private LocalImage loadFile(String fileName)
 {
     LocalImage img = new LocalImage();
     // loading image data in album
     if (extensions.Contains<String>(Path.GetExtension(fileName)))
     {
         FileInfo fi = new FileInfo(fileName);
         img.LocalFile = fi.FullName;
         img.Name = fi.Name;
         img.ConfidentialLevel = ModelManager.Instance.UploadOption.ConfidentialLevel;
         img.Author = ModelManager.Instance.UploadOption.Author;
         img.AuthorComment = "";
        }
     return img;
 }
Ejemplo n.º 18
0
 public DuplicateImage(LocalImage image, double percent)
 {
     Image = image;
     DuplicationPercent = percent;
 }