private void ApplyHaarTransform(bool forward, bool safe, int iterations, Bitmap bmp)
        {
            var maxScale = WaveletTransform.GetMaxScale(bmp.Width, bmp.Height);
            if (iterations < 1 || iterations > maxScale)
            {
                MessageBox.Show(string.Format("Iteration must be Integer from 1 to {0}", maxScale));
                return;
            }

            var time = Environment.TickCount;

            var channels = ColorChannels.CreateColorChannels(safe, bmp.Width, bmp.Height);

            var transform = WaveletTransform.CreateTransform(forward, iterations);

            var imageProcessor = new ImageProcessor(channels, transform);
            imageProcessor.ApplyTransform(bmp);

            if (forward)
            {
                this.TransformedImage = new Bitmap(bmp);
            }

            this.pictureBox1.Image = bmp;
            this.lblDirection.Text = forward ? "Forward" : "Inverse";
            this.lblTransformTime.Text = string.Format("{0} milis.", Environment.TickCount - time);
        }
Exemple #2
0
 public MainWindow()
 {
     InitializeComponent();
     CamProc = new ImageProcessor();
     CamProc.NewTargetPosition += new ImageProcessor.NewTargetPositionHandler(CamProc_NewTargetPosition);
     //Dispatcher.BeginInvoke((Action)(() => { Window_Loaded_Settings(); }), DispatcherPriority.Loaded, null);
     Dispatcher.BeginInvoke((Action)Window_Loaded_Settings, DispatcherPriority.Loaded, null);
 }
        public void Setup()
        {
            directory = new Mock<IDirectory>();

            settings = new SettingsContext();
            settings.AppRootDirectory = directory.Object;

            runner = new Mock<IImagePipelineRunner>();
            processor = new ImageProcessor(settings, runner.Object);
        }
        public void DecomposeWithUnsafeCode()
        {
            using (var originalImage = new Bitmap(OriginalFilename))
            {
                var transform = new ForwardWaveletTransform(1);
                var channels = new UnsafeColorChannels(originalImage.Width, originalImage.Height);
                var imageProcessor = new ImageProcessor(channels, transform);
                imageProcessor.ApplyTransform(originalImage);

                VerifyAsImage(originalImage);
            }
        }
    protected void UploadButton_Click(object sender, EventArgs e)
    {
        if (!ProductFileUpload.HasFile)
            return;
        String fileName = ProductFileUpload.FileName;
        if (!AllowedFiles.Contains(Path.GetExtension(fileName)))
            return;

        fileName = Server.UrlDecode(fileName);
        String savePath = HttpRuntime.AppDomainAppPath + @"\ProductImages\";
        savePath += fileName;

        ProductFileUpload.SaveAs(savePath);
        //Add to database and get back the ID
        CartDataClassesDataContext context = new CartDataClassesDataContext();
        InvertedSoftware.ShoppingCart.DataLayer.Dynamic.Image image = new InvertedSoftware.ShoppingCart.DataLayer.Dynamic.Image();
        image.ImageName = Path.GetFileName(savePath);
        image.ImageURL = fileName;
        image.ProductID = ProductID;
        image.SortOrder = 1;
        image.Active = true;
        context.Images.InsertOnSubmit(image);
        context.SubmitChanges();

        //Create a thumbnail
        ImageProcessor processor = new ImageProcessor();
        processor.ProcessedImage = (Bitmap)System.Drawing.Image.FromFile(savePath);
        processor.resizeImage(75, 75).Save(HttpRuntime.AppDomainAppPath + @"\ProductImages\" + Path.GetFileNameWithoutExtension(savePath) + "_t" + Path.GetExtension(savePath));
        processor.ProcessedImage.Dispose();
        processor.ProcessedImage = null;

        InvertedSoftware.ShoppingCart.DataLayer.Dynamic.Image thumnail = new InvertedSoftware.ShoppingCart.DataLayer.Dynamic.Image();
        thumnail.ParentID = image.ImageID;
        thumnail.ImageName = Path.GetFileNameWithoutExtension(savePath) + "_t";
        thumnail.ImageURL = Path.GetFileNameWithoutExtension(savePath) + "_t" + Path.GetExtension(savePath);
        thumnail.ProductID = ProductID;
        thumnail.SortOrder = 1;
        thumnail.Active = true;
        context.Images.InsertOnSubmit(thumnail);
        context.SubmitChanges();

        MessageLabel.Text = "Your file was saved as " + fileName + " <a href=\"Products/List.aspx\">Go back to Product list</a>";
    }
 public static void downloadPhoto(string url, string fileName, string description)
 {
     WebClient wc = new WebClient();
     try
     {
         StreamWriter sw = new StreamWriter(@"errors.txt", true);
         wc.DownloadFile(url, fileName);
         ImageProcessor processor = new ImageProcessor(fileName);
         ImageProperties properties = new ImageProperties();
         properties.Comments = description;
         if (!processor.TryWrite(properties))
             sw.WriteLine("couldn't write properties to image: " + fileName);
         sw.Flush();
         sw.Close();
     }
     catch (WebException e)
     {
         string shortenedFilename = fileName.Substring(0, 252);
         shortenedFilename += ".jpg";
         wc.DownloadFile(url, shortenedFilename);
     }
 }
Exemple #7
0
 public void GaussianFilter32BitTest()
 {
     double[] kernel = { 1.0 / 16, 1.0 / 8, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0 / 8, 1.0 / 16, 1.0 / 8, 1.0 / 16 };
     ImageProcessor.Filter(WorkingDirectory + "test32.bmp", WorkingDirectory + "ResultsOfNewProgram/gaussian32.bmp", kernel);
     FileAssert.AreEqual(WorkingDirectory + "ResultsOfNewProgram/gaussian32.bmp", WorkingDirectory + "ResultsOfLastProgram/gaussian32.bmp");
 }
Exemple #8
0
        public void LoadHitomi(string[] files)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => label.Visibility = Visibility.Hidden));
            if (files.Length <= 0)
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => label.Visibility = Visibility.Hidden));
                return;
            }
            string[] Folders      = FolderSort(files);
            int      i            = 0;
            int      SelectedPage = 1;

            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
                this.Background = new SolidColorBrush(Global.background);
                MainPanel.Children.Clear();
                if (SearchMode2.SelectedIndex == 1)
                {
                    Folders = Folders.Reverse().ToArray();
                }
                SelectedPage = Page_Index.SelectedIndex + 1;
                this.Title   = string.Format("MainWindow - {0}페이지", SelectedPage);
            }));
            foreach (string folder in Folders.Where(x => Array.IndexOf(Folders, x) + 1 <= Page_itemCount * SelectedPage && Array.IndexOf(Folders, x) + 1 > (SelectedPage - 1) * Page_itemCount))
            {
                i++;
                Console.WriteLine("{0}: {1}", i, folder);
                var      allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".lock" };
                string[] innerFiles        = Directory.GetFiles(folder).Where(file => allowedExtensions.Any(file.ToLower().EndsWith)).ToArray().ESort();
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                {
                    Hitomi h = new Hitomi
                    {
                        name        = folder.Split(Path.DirectorySeparatorChar).Last(),
                        dir         = folder,
                        page        = innerFiles.Length,
                        files       = innerFiles,
                        type        = Hitomi.Type.Folder,
                        FolderByte  = File2.GetFolderByte(folder),
                        SizePerPage = File2.GetSizePerPage(folder)
                    };
                    if (innerFiles.Length <= 0)
                    {
                        h.thumb     = ImageProcessor.FromResource("NoImage.jpg");
                        h.thumbpath = "";
                    }
                    else
                    {
                        h.thumb     = ImageProcessor.ProcessEncrypt(innerFiles.First());
                        h.thumbpath = innerFiles.First();
                    }
                    if (h.thumb == null)
                    {
                        return;
                    }
                    label.FontSize = 100;
                    label.Content  = i + "/" + Page_itemCount;
                    MainPanel.Children.Add(new HitomiPanel(h, this, true));
                    Console.WriteLine("Completed: {0}", folder);
                }));
            }
            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => label.Visibility = Visibility.Hidden));
        }
        public void CleanUp(System.ComponentModel.CancelEventArgs e = null, bool crash = false)
        {
            if (!crash)
            {
                for (int i = 0; i < graphs.Count; ++i)
                {
                    UIGraph        g   = graphs[i];
                    LayoutDocument doc = documents[i];
                    if (g.Modified && !g.ReadOnly)
                    {
                        var result = MessageBox.Show(this, g.GraphName + " " + Properties.Resources.TITLE_HAS_BEEN_MODIFIED, Properties.Resources.TITLE_SAVE_CHANGES, MessageBoxButton.YesNoCancel);
                        if (result == MessageBoxResult.Yes)
                        {
                            HandleSave(g, doc);
                        }
                        else if (result == MessageBoxResult.Cancel)
                        {
                            if (e != null)
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                    }
                }
            }

            recent.Save();

            //release all opengl content
            foreach (UIGraph g in graphs)
            {
                if (crash)
                {
                    if (!string.IsNullOrEmpty(g.FilePath))
                    {
                        if (g.FromArchive)
                        {
                            if (string.IsNullOrEmpty(g.FromArchivePath))
                            {
                                g.Save(g.FilePath + ".recovery.mtga", true);
                            }
                            else
                            {
                                g.Save(g.FromArchivePath + ".recovery.mtga", true);
                            }
                        }
                        else
                        {
                            g.Save(g.FilePath + ".recovery.mtg", true);
                        }
                    }
                }

                g.DeleteTempArchiveData();
                g.Release();
            }

            graphs.Clear();

            FontManager.Release();

            FunctionGraph.ReleaseShaderBuffer();
            //clear material and shader caches
            PBRMaterial.ReleaseBRDF();
            ImageProcessor.ReleaseAll();
            Material.Material.ReleaseAll();

            //release gl view
            if (UI3DPreview.Instance != null)
            {
                UI3DPreview.Instance.Release();
            }

            if (UIPreviewPane.Instance != null)
            {
                UIPreviewPane.Instance.Release();
            }

            ViewContext.Dispose();
        }
        public static void Vizual_Circle(ZArrayDescriptor zArrayDescriptor, PictureBox pictureBox01, int x0, int y0, int radius)
        {
            // c1 = ImageProcessor.getPixel(i, j, data1);                       // c1 = bmp1.GetPixel(i, j);
            // ImageProcessor.setPixel(data5, i, j, Color.FromArgb(r, r, r));   // bmp2.SetPixel(j, i, c1);
            // bmp5.UnlockBits(data5);
            if (pictureBox01 == null)
            {
                MessageBox.Show("pictureBox01 == null"); return;
            }
            if (zArrayDescriptor == null)
            {
                MessageBox.Show("ZArrayDescriptor array == null"); return;
            }

            int width  = zArrayDescriptor.width;
            int height = zArrayDescriptor.height;

            if (width == 0 || height == 0)
            {
                MessageBox.Show("width == 0 || height == 0"); return;
            }

            Bitmap     bmp2  = new Bitmap(width, height);
            BitmapData data2 = ImageProcessor.getBitmapData(bmp2);

            double max = SumClass.getMax(zArrayDescriptor);
            double min = SumClass.getMin(zArrayDescriptor);

            //MessageBox.Show("max = " + Convert.ToString(max) + " min = " + Convert.ToString(min));

            if (Math.Abs(max - min) < 0.0000001)
            {
                // MessageBox.Show("max = min");
                int c = 0;
                if (max < 255 && max > 0.0)
                {
                    c = Convert.ToInt32(max);
                }
                if (max > 255)
                {
                    c = 255;
                }
                if (max < 0)
                {
                    c = 0;
                }
                for (int j = 0; j < width; j++)
                {
                    for (int i = 0; i < height; i++)
                    {
                        Color c1 = Color.FromArgb(c, c, c);
                        ImageProcessor.setPixel(data2, j, i, c1);
                    }
                }
                pictureBox01.Image = bmp2;
                bmp2.UnlockBits(data2);
                return;
            }
            if (max != min)
            {
                double mxmn = 255.0 / (max - min);
                for (int j = 0; j < width; j++)
                {
                    for (int i = 0; i < height; i++)
                    {
                        int   c  = Convert.ToInt32((zArrayDescriptor.array[j, i] - min) * mxmn);
                        Color c1 = Color.FromArgb(c, c, c);
                        ImageProcessor.setPixel(data2, j, i, c1);
                    }
                }

                Color c2 = Color.FromArgb(255, 128, 255);
                DrawCircle(data2, x0, y0, radius, c2);                           // Рисование окружности  цветом

                Fill_Circle_Outside(zArrayDescriptor, data2, width, height, c2); // Заполнение цветом снаружи


                pictureBox01.Image = bmp2;
                bmp2.UnlockBits(data2);
                return;
            }
        }
Exemple #11
0
        private async Task ProcessImagesAsync(StorageFolder rootFolder)
        {
            this.progressRing.IsActive = true;

            this.AllResults.Clear();
            this.FilteredResults.Clear();
            this.TagFilters.Clear();
            this.EmotionFilters.Clear();
            this.FaceFilters.Clear();

            List <ImageInsights> insightsList = new List <ImageInsights>();

            // see if we have pre-computed results and if so load it from the json file
            try
            {
                StorageFile insightsResultFile = (await rootFolder.TryGetItemAsync("ImageInsights.json")) as StorageFile;
                if (insightsResultFile != null)
                {
                    using (StreamReader reader = new StreamReader(await insightsResultFile.OpenStreamForReadAsync()))
                    {
                        insightsList = JsonConvert.DeserializeObject <List <ImageInsights> >(await reader.ReadToEndAsync());
                        foreach (var insights in insightsList)
                        {
                            await AddImageInsightsToViewModel(rootFolder, insights);
                        }
                    }
                }
            }
            catch
            {
                // We will just compute everything again in case of errors
            }

            if (!insightsList.Any())
            {
                // start with fresh face lists
                await FaceListManager.ResetFaceLists();

                // enumerate through the first 50 images and extract the insights
                QueryOptions           fileQueryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".png", ".jpg", ".bmp", ".jpeg", ".gif" });
                StorageFileQueryResult queryResult      = rootFolder.CreateFileQueryWithOptions(fileQueryOptions);
                foreach (var item in (await queryResult.GetFilesAsync(0, 50)))
                {
                    try
                    {
                        // Resize (if needed) in order to reduce network latency and errors due to large files. Then store the result in a temporary file.
                        StorageFile resizedFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("ImageCollectionInsights.jpg", CreationCollisionOption.GenerateUniqueName);

                        var resizeTransform = await Util.ResizePhoto(await item.OpenStreamForReadAsync(), 720, resizedFile);

                        // Send the file for processing
                        ImageInsights insights = await ImageProcessor.ProcessImageAsync(resizedFile.OpenStreamForReadAsync, item.Name);

                        // Delete resized file
                        await resizedFile.DeleteAsync();

                        // Adjust all FaceInsights coordinates based on the transform function between the original and resized photos
                        foreach (var faceInsight in insights.FaceInsights)
                        {
                            faceInsight.FaceRectangle.Left   = (int)(faceInsight.FaceRectangle.Left * resizeTransform.Item1);
                            faceInsight.FaceRectangle.Top    = (int)(faceInsight.FaceRectangle.Top * resizeTransform.Item2);
                            faceInsight.FaceRectangle.Width  = (int)(faceInsight.FaceRectangle.Width * resizeTransform.Item1);
                            faceInsight.FaceRectangle.Height = (int)(faceInsight.FaceRectangle.Height * resizeTransform.Item2);
                        }

                        insightsList.Add(insights);
                        await AddImageInsightsToViewModel(rootFolder, insights);
                    }
                    catch (Exception ex)
                    {
                        await Util.GenericApiCallExceptionHandler(ex, "Error processing image.");
                    }
                }

                // save to json
                StorageFile jsonFile = await rootFolder.CreateFileAsync("ImageInsights.json", CreationCollisionOption.ReplaceExisting);

                using (StreamWriter writer = new StreamWriter(await jsonFile.OpenStreamForWriteAsync()))
                {
                    string jsonStr = JsonConvert.SerializeObject(insightsList, Formatting.Indented);
                    await writer.WriteAsync(jsonStr);
                }
            }

            var sortedTags = this.TagFilters.OrderBy(t => t.Tag).ToArray();

            this.TagFilters.Clear();
            this.TagFilters.AddRange(sortedTags);

            var sortedEmotions = this.EmotionFilters.OrderBy(t => t.Emotion).ToArray();

            this.EmotionFilters.Clear();
            this.EmotionFilters.AddRange(sortedEmotions);

            this.progressRing.IsActive = false;
        }
Exemple #12
0
 private async void Image_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Right)
     {
         if (page < hitomi.page - 1)
         {
             page++;
         }
     }
     else if (e.Key == Key.Left)
     {
         if (page > 0)
         {
             page--;
         }
     }
     if (e.Key == Key.Right || e.Key == Key.Left)
     {
         PreLoad();
         SetImage(hitomi.files[page]);
     }
     if (e.Key == Key.F11)
     {
         //Normal
         if (WindowStyle == WindowStyle.None && WindowState == WindowState.Maximized)
         {
             this.WindowStyle = WindowStyle.SingleBorderWindow;
             this.WindowState = WindowState.Normal;
         }
         else if (WindowStyle == WindowStyle.SingleBorderWindow && WindowState == WindowState.Normal)
         {
             this.WindowStyle = WindowStyle.None;
             this.WindowState = WindowState.Maximized;
         }
         //Maximized
         else if (WindowStyle == WindowStyle.SingleBorderWindow && WindowState == WindowState.Maximized)
         {
             this.WindowStyle = WindowStyle.None;
             this.WindowState = WindowState.Normal;
             this.WindowState = WindowState.Maximized;
         }
     }
     else if (e.Key == Key.Escape)
     {
         if (WindowStyle == WindowStyle.None && WindowState == WindowState.Maximized)
         {
             this.WindowStyle = WindowStyle.SingleBorderWindow;
             this.WindowState = WindowState.Normal;
         }
     }
     else if (e.Key == Key.Enter)
     {
         Uri  uriResult;
         bool result = Uri.TryCreate(hitomi.dir, UriKind.Absolute, out uriResult) &&
                       ((uriResult.Scheme == Uri.UriSchemeHttp) || (uriResult.Scheme == Uri.UriSchemeHttps));
         if (result)
         {
             try
             {
                 this.Title = hitomi.name + " 0/" + (hitomi.files.Length - 1);
                 for (int i = 0; i < hitomi.files.Length; i++)
                 {
                     this.Title = hitomi.name + " " + i + "/" + (hitomi.files.Length - 1);
                     if (hitomi.images == null || hitomi.images.Length < hitomi.page)
                     {
                         hitomi.images = new BitmapImage[hitomi.page];
                     }
                     if (hitomi.images[i] == null)
                     {
                         hitomi.images[i] = await ImageProcessor.ProcessEncryptAsync(hitomi.files[i]);
                     }
                 }
             }
             catch { }
         }
     }
     if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.C)
     {
         Clipboard.SetImage((BitmapSource)this.image.Source);
     }
 }
 public CompositionModelProcessor(Template pattern, ImageProcessor imageProcessor, ImageUtils imageUtils)
 {
     _pattern        = pattern;
     _imageProcessor = imageProcessor;
     _imageUtils     = imageUtils;
 }
Exemple #14
0
 public IndoorCamFacade()
 {
     ImgP      = new ImageProcessor();
     SoundP    = new SoundProcessor();
     CamDriver = new CameraDriver();
 }
        public void FullProcessWithAutoAdjustTest()
        {
            var stopwatch = Stopwatch.StartNew();
            const int maxIter = 5;
            for (var iter = 0; iter < maxIter; iter++)
            {
                var stream = new FileStream(@"..\..\..\PanasonicRW2.Tests\P1350577.RW2", FileMode.Open,
                    FileAccess.Read);
                var debayer = new AverageBGGRDemosaic();

                var white = new WhiteBalanceFilter();
                //white.AutoAdjust(color16Image);
                var gamma = new GammaFilter();

                var light = new LightFilter();
                //light.AutoAdjust(color16Image);

                var compressor = new VectorBGRACompressorFilter();
                var filters = new IFilter[]
                {
                    debayer,
                    //white,
                    gamma,
                    light,
                    compressor
                };

                var decoder = new PanasonicRW2Decoder();
                var exif = decoder.DecodeExif(stream);

                var processor = new ImageProcessor(decoder.DecodeMap(stream, exif), filters);

                processor.Invoke();
            }
            stopwatch.Stop();
            Console.WriteLine("FullProcessWithAutoAdjust: " + stopwatch.ElapsedMilliseconds / maxIter + "ms");

            //Before Curve - Release 3756ms
            //After Curve - Release 1900ms
            //2015 Vector3 - Release 1305ms
        }
Exemple #16
0
 public void Grayscale32BitTest()
 {
     ImageProcessor.ReadGrayscaleAndWriteImage(WorkingDirectory + "test32.bmp", WorkingDirectory + "ResultsOfNewProgram/grayscale32.bmp");
     FileAssert.AreEqual(WorkingDirectory + "ResultsOfNewProgram/grayscale32.bmp", WorkingDirectory + "ResultsOfLastProgram/grayscale32.bmp");
 }
        public void FullRecomposeWithSafeCode()
        {
            using (var originalImage = new Bitmap(DecomposedFilename))
            {
                var width = originalImage.Width;
                var height = originalImage.Height;
                var transform = new InverseWaveletTransform(width, height);
                var channels = new SafeColorChannels(width, height);
                var imageProcessor = new ImageProcessor(channels, transform);
                imageProcessor.ApplyTransform(originalImage);

                VerifyAsImage(originalImage);
            }
        }
Exemple #18
0
        private void buttonHough_Click(object sender, EventArgs e)
        {
            //var houghFinder = new HoughCircle();
            //houghFinder.init(_sourceImage, 160);
            //houghFinder.process();
            //_filteredPictureBox.Image = houghFinder.GetBitmapResult();
            //_filteredPictureBox.Update();

            var imageProcessor = new ImageProcessor();
            imageProcessor.CurrentBitmap = (Bitmap)_sourcePictureBox.Image;
            imageProcessor.SequentialScan();
            //MessageBox.Show(imageProcessor.Shapes.Count.ToString());
            _filteredPictureBox.Image = imageProcessor.GetMarkedBitmap();
            _filteredPictureBox.Update();
            MessageBox.Show("ShowCircles");
            Bitmap result;
            _circlePoints = imageProcessor.GetCirclePoints(_loadedBitmap.Clone() as Bitmap, out result);
            _filteredPictureBox.Image = result;
            _filteredPictureBox.Update();
        }
        private void PostFile()
        {
            bool thumbUploaded = false, posterUploaded = false;
            string destFolder = mediaConfig.TempLocationFolder;
            var originFileInfo = new FileInfo(FileToUpload.PostedFile.FileName);
            try
            {

                using (SPLongOperation longOperation = new SPLongOperation(this.Page))
                {
                    SPWeb web = SPContext.Current.Web;
                    MediaAsset asset = MediaAsset.FromFile(originFileInfo, SPContext.Current.Web.Url, mediaConfig);
                    longOperation.Begin();

                    asset.FileSize = FileToUpload.PostedFile.ContentLength;

                    var validator = ValidatorFactory.GetValidator(asset.MediaType, mediaConfig);
                    validator.ValidateFileSize(asset.FileSize);
                    IAssetStorageManager storage = AssetStorageFactory.GetStorageManager("Media", web.Url);
                    string newFileUniqueNameWithoutExtension = Guid.NewGuid().ToString();
                    string newFileUniqueName = String.Concat(newFileUniqueNameWithoutExtension, originFileInfo.Extension);

                    //upload optional images
                    if (ThumbnailInput.PostedFile != null && !String.IsNullOrEmpty(ThumbnailInput.PostedFile.FileName))
                    {
                        string thumbFileName = MediaConfig.GetThumbnailFileName(newFileUniqueNameWithoutExtension, ThumbnailInput.PostedFile.FileName);
                        asset.Thumbnail = storage.Save(thumbFileName, ThumbnailInput.PostedFile.InputStream);
                        thumbUploaded = true;
                    }
                    if (PosterInput.PostedFile != null && !String.IsNullOrEmpty(PosterInput.PostedFile.FileName))
                    {
                        string posterFileName = MediaConfig.GetPosterFileName(newFileUniqueNameWithoutExtension, PosterInput.PostedFile.FileName);
                        asset.Poster = storage.Save(posterFileName, PosterInput.PostedFile.InputStream);
                        posterUploaded = true;
                    }
                    //upload principal file
                    if (asset.MediaType == MediaType.Image)
                    {
                        if (!thumbUploaded)//no thumb image was uploaded
                        {
                            //generate thumb & save
                            ImageProcessor imgProc = new ImageProcessor();
                            using (MemoryStream thumbStream = new MemoryStream())
                            {
                                string thumbFileName = MediaConfig.GetThumbnailFileName(newFileUniqueNameWithoutExtension);
                                imgProc.GenerateThumbnail(FileToUpload.PostedFile.InputStream, thumbStream);
                                thumbStream.Position = 0;
                                asset.Thumbnail = storage.Save(thumbFileName, thumbStream);
                            }
                            FileToUpload.PostedFile.InputStream.Position = 0;
                        }
                        //save to final location
                        asset.Location = storage.Save(newFileUniqueName, FileToUpload.PostedFile.InputStream);
                        asset.Status = ProcessingStatus.Success;
                    }
                    else
                    {
                        var tempFileInfo = new FileInfo(Path.Combine(destFolder, newFileUniqueName));

                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            //save to file system
                            FileToUpload.PostedFile.SaveAs(tempFileInfo.FullName);
                            asset.TempLocation = tempFileInfo.FullName;
                            asset.Duration = MediaLengthCalculator.GetMediaLength(tempFileInfo);
                        });
                        try
                        {
                            validator.ValidateLength(asset.Duration);
                        }
                        catch (MediaTooLargeException)
                        {
                            FileUtils.Delete(tempFileInfo);
                            throw;
                        }
                        if (asset.MediaType == MediaType.Audio)
                        {
                            asset.Location = storage.Save(newFileUniqueName, FileToUpload.PostedFile.InputStream);
                            FileUtils.Delete(tempFileInfo);
                            asset.TempLocation = String.Empty;
                            if (!thumbUploaded)//no thumb image was uploaded, upload default
                            {
                                string thumbnailFileName = MediaConfig.GetThumbnailFileName(newFileUniqueNameWithoutExtension, mediaConfig.DefaultAudioThumbnail);
                                SPFile thumbImg = web.GetFile(mediaConfig.DefaultAudioThumbnail);
                                asset.Thumbnail = storage.Save(thumbnailFileName, thumbImg.OpenBinaryStream());
                            }
                            if (!posterUploaded)//no poster image was uploaded, upload default
                            {
                                string posterFileName = MediaConfig.GetPosterFileName(newFileUniqueNameWithoutExtension, mediaConfig.DefaultAudioPoster);
                                SPFile thumbImg = web.GetFile(web.Url + mediaConfig.DefaultAudioPoster);
                                asset.Poster = storage.Save(posterFileName, thumbImg.OpenBinaryStream());
                            }
                            asset.Status = ProcessingStatus.Success;
                        }
                        else if (asset.MediaType == MediaType.Video && !mediaConfig.EncodeVideoFlag && thumbUploaded && posterUploaded)
                        {
                            //video doesn't need encoding, nor generation of thumb and poster images => upload file and set status as processed.
                            asset.Location = storage.Save(newFileUniqueName, FileToUpload.PostedFile.InputStream);
                            FileUtils.Delete(tempFileInfo);
                            asset.TempLocation = String.Empty;
                            asset.Status = ProcessingStatus.Success;
                        }
                    }
                    var list = web.Lists[mediaConfig.MediaAssetsListName];
                    int id;
                    string contentTypeId;
                    mediaRepository.Insert(list, asset, out id, out contentTypeId);
                    string url = String.Format("{0}?ID={1}&ContentTypeId={2}", list.DefaultEditFormUrl, id, contentTypeId);
                    longOperation.End(url);
                }
            }
            catch (ThreadAbortException) { /* Thrown when redirected */}
            catch (Exception ex)
            {
                logger.LogToOperations(ex, LogCategories.Media, EventSeverity.Error, "Error uploading media '{0}'", FileToUpload.PostedFile.FileName);
                SPUtility.TransferToErrorPage(ex.ToString());
            }
        }
        private void LoadImage()
        {
            var processor = new ImageProcessor(this.filePath, this.presenter.Configuration);

            this.MainImage.Source = processor.GetImage();
        }
        private Bitmap ApplyHaarTransform(bool forward, bool safe, int iterations, Bitmap bmp)
        {
            var maxScale = WaveletTransform.GetMaxScale(bmp.Width, bmp.Height);
            if (iterations < 1 || iterations > maxScale)
            {
                MessageBox.Show(string.Format("Iteration must be Integer from 1 to {0}", maxScale));
                return new Bitmap(bmp.Width, bmp.Height);
            }

            var channels = ColorChannels.CreateColorChannels(safe, bmp.Width, bmp.Height);

            var transform = WaveletTransform.CreateTransform(forward, iterations);

            var imageProcessor = new ImageProcessor(channels, transform);
            imageProcessor.ApplyTransform(bmp);
            return bmp;
        }
        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            pictureBox_Result.Image = null;
            textBox_Info.Text = String.Empty;
            textBox_Classterize.Text = String.Empty;
            fileName = (sender as OpenFileDialog).FileName;
            var image = Bitmap.FromFile(fileName) as Bitmap;
            pictureBox_Base.Image = image as Image;

            imageProcessor = new ImageProcessor(image);
            var gistogram = imageProcessor.Gistogram;
            baseImage = imageProcessor.Image;

            zedGraphControl.GraphPane.CurveList.Clear();
            zedGraphControl.GraphPane.AddCurve("",
                gistogram.Keys
                    .Select(x => new { value = (double)x })
                    .Select(x => x.value).ToArray(),
                gistogram.Values
                    .Select(x => new { value = (double)x })
                    .Select(x => x.value).ToArray(),
                Color.Black);
            zedGraphControl.GraphPane.Title.Text = "Gistogram";
            zedGraphControl.GraphPane.XAxis.Scale.Min = 0;
            zedGraphControl.GraphPane.XAxis.Scale.Max = 255;
            zedGraphControl.AxisChange();
            zedGraphControl.Refresh();

            processingToolStripMenuItem.Enabled = true;
        }
    // Use this for initialization
    void Start()
    {
        if (Instance != null)
        {
            Debug.LogWarning("Two instances of signleton exist in this scene.", this);
            Destroy(this.gameObject);
            return;
        }
        Instance = this;

        int nPixels = m_filteredDepthImage.m_width * m_filteredDepthImage.m_height;
        m_rawDepthData = new short[nPixels];
        m_rawDepthDataNormalized = new float[nPixels];

        m_filteredDepthImage.name = "FilteredDepthImage";
        m_filteredDepthImage.m_source.wrapMode = TextureWrapMode.Clamp;
    }
        void BuildRGB()
        {
            Log.Trace($"BuildRGB called");
            lock (this)
            {
                if (rgbmap == null)
                {
                    var map = ReadRaw();

                    var filters = PrepareFilters();

                    var processor = new ImageProcessor(map, filters);
                    rgbmap = (ColorMap<BGRA8>)processor.Invoke();
                    map.Dispose();
                }
            }
            Log.Trace("BuildRGB finished");
        }
Exemple #25
0
    // Update is called once per frame
    void Update()
    {
        if (webCamTexture.didUpdateThisFrame)
        {
            Color[] color = webCamTexture.GetPixels();
            if (first == 0)
            {
                w                  = webCamTexture.width;
                h                  = webCamTexture.height;
                texture            = new Texture2D(w, h);
                videoImage.texture = texture;
                videoImage.material.mainTexture = texture;
            }
            ImageProcessor processor   = new ImageProcessor(w, h, webCamTexture, texture);
            Manager        manager     = GameObject.Find("Manager").GetComponent <Manager> ();
            int            captSize    = (int)(90 * (1 - manager.captureMax)) + 10;
            bool           showall     = GameObject.Find("Video Toggle").GetComponent <Toggle> ().isOn;
            int            minDrawSize = 0;
            if (!showall)
            {
                minDrawSize = captSize;
            }
            if (is_recognizing)
            {
                bool       flag  = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks).TotalSeconds <= 5;
                List <int> indst = new List <int> (manager.Patterns.Count + 1);
                List <RecognizedPatternImage> recognized = new List <RecognizedPatternImage> (1000);
                processor.ProcessImage(captSize, manager.minThr, manager.maxThr, manager.filterSize, minDrawSize);
                processor.RecognizePatterns((int)(90 * manager.captureMin) + 10, captSize, manager.Patterns, indst, recognized, null);
                List <int> indstgr = new List <int> (manager.LowGroups.Count + 1);
                List <RecognizedPatternGroup> recognizedgr = new List <RecognizedPatternGroup> (1000);
                processor.RecognizeGroups((int)(90 * manager.captureMin) + 10, captSize, manager.LowGroups, indstgr, recognizedgr);
                is_recognizing = flag;
                List <int> iall = new List <int> (manager.Patterns.Count + 1);
                List <RecognizedPattern> all = new List <RecognizedPattern> (1000);
                processor.RecognizeAll(captSize, indst, recognized, indstgr, recognizedgr, manager.PatternsToRecognize, iall, all);
                if (all.Count > 0)
                {
                    for (int i = 0; i < all.Count; i++)
                    {
                        RecognizedPattern rp = all [i];
                        int rpc = 1;
                        RecognizedPatternGroup rpg = null;
                        if (rp is RecognizedPatternGroup)
                        {
                            rpg = (RecognizedPatternGroup)rp;
                            rpc = rpg.Count;
                        }
                        bool hit = false;
                        for (int j = 0; j < scores.Count; j++)
                        {
                            if (indcs [j].Count == rpc)
                            {
                                hit = true;
                                if (rpg == null)
                                {
                                    hit = rp.Pattern.Id == indcs [j] [0];
                                }
                                else
                                {
                                    for (int k = 0; k < rpc; k++)
                                    {
                                        if (rpg [k].Pattern.Id != indcs [j] [k])
                                        {
                                            hit = false;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (hit)
                            {
                                scores [j] += (1 - rp.Score);
                                break;
                            }
                        }
                        if (!hit)
                        {
                            scores.Add(1 - rp.Score);
                            indcs.Add(new List <int> (rpc));
                            String name = "";
                            if (rpg == null)
                            {
                                indcs [scores.Count - 1].Add(rp.Pattern.Id);
                                name = Pattern.GetName(rp.Pattern.Id);
                            }
                            else
                            {
                                for (int k = 0; k < rpc; k++)
                                {
                                    indcs [scores.Count - 1].Add(rpg [k].Pattern.Id);
                                    name += Pattern.GetName(rpg [k].Pattern.Id);
                                }
                            }
                            names.Add(name);
                        }
                    }
                    int maxi = 0;
                    for (int i = 1; i < scores.Count; i++)
                    {
                        if (scores [i] > scores [maxi])
                        {
                            maxi = i;
                        }
                    }
                    GameObject.Find("AnswerText").GetComponent <Text> ().text = names [maxi];
                }
            }
            else if (showall)
            {
                texture.SetPixels(webCamTexture.GetPixels());
                processor.DrawCaptureBox(captSize);
            }
            texture.Apply();

            first++;
        }
    }
        private void ProcessBitmap(Bitmap bitmap)
        {
            if (bitmap != null)
            {
                ImageProcessor faceDetectionProcessor = new ImageProcessor(bitmap);
                faceDetectionProcessor.FindSkinPixelsRGB();
                faceDetectionProcessor.Binarize(1);
                double[,] imageMatrix = faceDetectionProcessor.AsGrayMatrix();
                List <Tuple <int, int> > horizontalPositionSkinPixelTupleList = new List <Tuple <int, int> >();
                List <int> horizontalSkinPixelList = new List <int>();
                for (int ii = 0; ii < bitmap.Width; ii++)
                {
                    int skinPixels = 0;
                    for (int jj = 0; jj < bitmap.Height; jj++)
                    {
                        if (imageMatrix[ii, jj] > 0)
                        {
                            skinPixels++;
                        }
                    }
                    //    if (skinPixels > 1)
                    //    {
                    Tuple <int, int> horizontalPositionSkinPixelTuple = new Tuple <int, int>(ii, skinPixels);
                    horizontalPositionSkinPixelTupleList.Add(horizontalPositionSkinPixelTuple);
                    horizontalSkinPixelList.Add(skinPixels);
                    //   }
                }
                List <int> verticalSkinPixelList = new List <int>();
                for (int jj = 0; jj < bitmap.Height; jj++)
                {
                    int skinPixels = 0;
                    for (int ii = 0; ii < bitmap.Width; ii++)
                    {
                        if (imageMatrix[ii, jj] > 0)
                        {
                            skinPixels++;
                        }
                    }
                    verticalSkinPixelList.Add(skinPixels);
                }
                if (horizontalPositionSkinPixelTupleList.Count > 0)
                {
                    horizontalPositionSkinPixelTupleList.Sort((a, b) => a.Item2.CompareTo(b.Item2));
                    horizontalPositionSkinPixelTupleList.Reverse();
                    faceCenterHorizontalPosition = 0;
                    double centerFraction = 0.8;
                    double maxValue       = horizontalPositionSkinPixelTupleList[0].Item2;
                    int    index          = 0;
                    double thresholdValue = (int)(centerFraction * maxValue);
                    while (horizontalPositionSkinPixelTupleList[index].Item2 >= thresholdValue)
                    {
                        faceCenterHorizontalPosition += horizontalPositionSkinPixelTupleList[index].Item1;
                        index++;
                        if (index >= horizontalPositionSkinPixelTupleList.Count)
                        {
                            break;
                        }
                    }
                    faceCenterHorizontalPosition /= index;
                    int    faceCenterIntHorizontalPosition = (int)Math.Round(faceCenterHorizontalPosition);
                    double edgeFraction            = 0.25;
                    double edgeThreshold           = (int)(edgeFraction * maxValue);
                    int    horizontalScanLineIndex = faceCenterIntHorizontalPosition;
                    double scanLineSkinPixels      = horizontalSkinPixelList[faceCenterIntHorizontalPosition];
                    while (scanLineSkinPixels > edgeThreshold)
                    {
                        horizontalScanLineIndex++;
                        if (horizontalScanLineIndex >= horizontalSkinPixelList.Count)
                        {
                            break;
                        }
                        scanLineSkinPixels = horizontalSkinPixelList[horizontalScanLineIndex];
                    }
                    int rightEdge = horizontalScanLineIndex;
                    if (rightEdge >= bitmap.Width)
                    {
                        rightEdge = bitmap.Width - 1;
                    }
                    horizontalScanLineIndex = faceCenterIntHorizontalPosition;
                    scanLineSkinPixels      = horizontalSkinPixelList[faceCenterIntHorizontalPosition];
                    while (scanLineSkinPixels > edgeThreshold)
                    {
                        horizontalScanLineIndex--;
                        if (horizontalScanLineIndex < 0)
                        {
                            break;
                        }
                        scanLineSkinPixels = horizontalSkinPixelList[horizontalScanLineIndex];
                    }
                    int leftEdge = horizontalScanLineIndex;
                    if (leftEdge < 0)
                    {
                        leftEdge = 0;
                    }

                    int maximumVerticalSkinPixels = verticalSkinPixelList.Max();
                    int maximumVerticalIndex      = verticalSkinPixelList.IndexOf(maximumVerticalSkinPixels);
                    edgeThreshold = (int)(edgeFraction * maximumVerticalSkinPixels);
                    int verticalScanLineIndex = maximumVerticalIndex;
                    int verticalSkinPixels    = verticalSkinPixelList[verticalScanLineIndex];
                    while (verticalSkinPixels > edgeThreshold)
                    {
                        verticalScanLineIndex--;
                        if (verticalScanLineIndex <= 0)
                        {
                            break;
                        }
                        verticalSkinPixels = verticalSkinPixelList[verticalScanLineIndex];
                    }

                    /*   int verticalScanLineIndex = 0;
                     * int verticalSkinPixels = verticalSkinPixelList[verticalScanLineIndex];
                     * while (verticalSkinPixels  < edgeThreshold)
                     * {
                     *     verticalScanLineIndex++;
                     *     if (verticalScanLineIndex >= verticalSkinPixelList.Count) { break; }
                     *     verticalSkinPixels = verticalSkinPixelList[verticalScanLineIndex];
                     * }  */
                    int topEdge        = verticalScanLineIndex;
                    int width          = rightEdge - leftEdge;
                    int heightEstimate = (int)Math.Round(1.3 * width);
                    int bottomEdge     = topEdge + heightEstimate;
                    if (bottomEdge >= bitmap.Height)
                    {
                        bottomEdge = bitmap.Height - 1;
                    }
                    OnFaceCenterPositionAvailable(faceCenterIntHorizontalPosition);

                    centerHorizontalPositionList.RemoveAt(0);
                    centerHorizontalPositionList.Add(faceCenterIntHorizontalPosition);
                    double  min          = centerHorizontalPositionList.Min();
                    double  max          = centerHorizontalPositionList.Max();
                    Boolean lockAcquired = false;
                    if (((faceCenterIntHorizontalPosition - min) < 10) && ((max - faceCenterIntHorizontalPosition) < 10))
                    {
                        lockAcquired = true;
                    }
                    OnFaceBoundingBoxAvailable(leftEdge, rightEdge, topEdge, bottomEdge, lockAcquired);
                }
                faceDetectionProcessor.Release();
            }
        }
Exemple #27
0
 public AlbumsModel(AlbumCollection ac, IHostingEnvironment environment, ImageProcessor processor)
 {
     _ac          = ac;
     _environment = environment;
     _processor   = processor;
 }
Exemple #28
0
        public ActionResult Index(short[] characteristicLinkIds, string[] customSequences, bool localFile, string fileType, bool toLower, bool removePunctuation)
        {
            return(CreateTask(() =>
            {
                int sequencesCount = localFile ? Request.Files.Count : customSequences.Length;
                var sequencesNames = new string[sequencesCount];
                var sequences = new Chain[sequencesCount];
                if (localFile)
                {
                    for (int i = 0; i < sequencesCount; i++)
                    {
                        Stream sequenceStream = FileHelper.GetFileStream(Request.Files[i]);
                        sequencesNames[i] = Request.Files[i].FileName;

                        switch (fileType)
                        {
                        case "text":
                            using (var sr = new StreamReader(sequenceStream))
                            {
                                string stringTextSequence = sr.ReadToEnd();
                                if (toLower)
                                {
                                    stringTextSequence = stringTextSequence.ToLower();
                                }
                                if (removePunctuation)
                                {
                                    stringTextSequence = Regex.Replace(stringTextSequence, @"[^\w\s]", "");
                                }
                                sequences[i] = new Chain(stringTextSequence);
                            }
                            break;

                        case "image":
                            var image = Image.Load(sequenceStream);
                            var sequence = ImageProcessor.ProcessImage(image, new IImageTransformer[0], new IMatrixTransformer[0], new LineOrderExtractor());
                            var alphabet = new Alphabet {
                                NullValue.Instance()
                            };
                            var incompleteAlphabet = sequence.Alphabet;
                            for (int j = 0; j < incompleteAlphabet.Cardinality; j++)
                            {
                                alphabet.Add(incompleteAlphabet[j]);
                            }

                            sequences[i] = new Chain(sequence.Building, alphabet);
                            break;

                        case "genetic":
                            ISequence fastaSequence = NcbiHelper.GetFastaSequence(sequenceStream);
                            var stringSequence = fastaSequence.ConvertToString();
                            sequences[i] = new Chain(stringSequence);
                            sequencesNames[i] = fastaSequence.ID;
                            break;

                        case "wavFile":
                            var reader = new BinaryReader(Request.Files[i].InputStream);

                            int chunkID = reader.ReadInt32();
                            int fileSize = reader.ReadInt32();
                            int riffType = reader.ReadInt32();
                            int fmtID = reader.ReadInt32();
                            int fmtSize = reader.ReadInt32();
                            int fmtCode = reader.ReadInt16();
                            int channels = reader.ReadInt16();
                            int sampleRate = reader.ReadInt32();
                            int fmtAvgBPS = reader.ReadInt32();
                            int fmtBlockAlign = reader.ReadInt16();
                            int bitDepth = reader.ReadInt16();

                            if (fmtSize == 18)
                            {
                                // Read any extra values
                                int fmtExtraSize = reader.ReadInt16();
                                reader.ReadBytes(fmtExtraSize);
                            }

                            int dataID = reader.ReadInt32();
                            int dataSize = reader.ReadInt32();
                            byte[] byteArray = reader.ReadBytes(dataSize);
                            var shortArray = new short[byteArray.Length / 2];
                            Buffer.BlockCopy(byteArray, 0, shortArray, 0, byteArray.Length);
                            //shortArray = Amplitude(shortArray, 20);
                            shortArray = Sampling(shortArray, 50);
                            //shortArray = shortArray.Select(s => (short)(s / 10)).ToArray();
                            sequences[i] = new Chain(shortArray);
                            break;

                        default:
                            throw new ArgumentException("Unknown file type", nameof(fileType));
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sequencesCount; i++)
                    {
                        sequences[i] = new Chain(customSequences[i]);
                        sequencesNames[i] = $"Custom sequence {i + 1}. Length: {customSequences[i].Length}";
                    }
                }

                var sequencesCharacteristics = new SequenceCharacteristics[sequences.Length];
                for (int j = 0; j < sequences.Length; j++)
                {
                    var characteristics = new double[characteristicLinkIds.Length];
                    for (int k = 0; k < characteristicLinkIds.Length; k++)
                    {
                        Link link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkIds[k]);
                        FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkIds[k]);
                        IFullCalculator calculator = FullCalculatorsFactory.CreateCalculator(characteristic);

                        characteristics[k] = calculator.Calculate(sequences[j], link);
                    }

                    sequencesCharacteristics[j] = new SequenceCharacteristics
                    {
                        MatterName = sequencesNames[j],
                        Characteristics = characteristics
                    };
                }

                var characteristicNames = new string[characteristicLinkIds.Length];
                var characteristicsList = new SelectListItem[characteristicLinkIds.Length];
                for (int k = 0; k < characteristicLinkIds.Length; k++)
                {
                    characteristicNames[k] = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkIds[k]);
                    characteristicsList[k] = new SelectListItem
                    {
                        Value = k.ToString(),
                        Text = characteristicNames[k],
                        Selected = false
                    };
                }

                var result = new Dictionary <string, object>
                {
                    { "characteristics", sequencesCharacteristics },
                    { "characteristicNames", characteristicNames },
                    { "characteristicsList", characteristicsList }
                };

                return new Dictionary <string, object>
                {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
 public lab11(PictureBox pb)
 {
     InitializeComponent();
     _imageProcessor = new ImageProcessor();
     resPB           = pb;
 }
        //---------------------------------------------------------------------------------------------------------------------
        //
        //         Из ZArrayDescriptor.array в PictureBox
        //
        public static void Vizual_Picture(ZArrayDescriptor zArrayDescriptor, PictureBox pictureBox01)
        {
            // c1 = ImageProcessor.getPixel(i, j, data1);                       // c1 = bmp1.GetPixel(i, j);
            // ImageProcessor.setPixel(data5, i, j, Color.FromArgb(r, r, r));   // bmp2.SetPixel(j, i, c1);
            // bmp5.UnlockBits(data5);

            if (pictureBox01 == null)
            {
                MessageBox.Show("Vizual_Picture: pictureBox01 == null"); return;
            }
            if (zArrayDescriptor == null)
            {
                MessageBox.Show("Vizual_Picture: ZArrayDescriptor array == null"); return;
            }

            int width  = zArrayDescriptor.width;
            int height = zArrayDescriptor.height;

            if (width == 0 || height == 0)
            {
                MessageBox.Show("Vizual_Picture: width == 0 || height == 0"); return;
            }

            Bitmap     bmp2  = new Bitmap(width, height);
            BitmapData data2 = ImageProcessor.getBitmapData(bmp2);

            double max = SumClass.getMax(zArrayDescriptor);
            double min = SumClass.getMin(zArrayDescriptor);

            //MessageBox.Show("max = " + Convert.ToString(max) + " min = " + Convert.ToString(min));

            if (Math.Abs(max - min) < 0.0000001)
            {
                // MessageBox.Show("max = min");
                int c = 0;
                if (max < 255 && max > 0.0)
                {
                    c = Convert.ToInt32(max);
                }
                if (max > 255)
                {
                    c = 255;
                }
                if (max < 0)
                {
                    c = 0;
                }
                for (int j = 0; j < width; j++)
                {
                    for (int i = 0; i < height; i++)
                    {
                        Color c1 = Color.FromArgb(c, c, c);
                        ImageProcessor.setPixel(data2, j, i, c1);
                    }
                }
                pictureBox01.Image = bmp2;
                bmp2.UnlockBits(data2);
                return;
            }

            if (max != min)
            {
                double mxmn = 255.0 / (max - min);
                for (int j = 0; j < width; j++)
                {
                    for (int i = 0; i < height; i++)
                    {
                        int c;
                        try
                        {
                            c = Convert.ToInt32((zArrayDescriptor.array[j, i] - min) * mxmn);
                        }
                        catch (System.OverflowException)
                        {
                            c = 0;
                        }

                        Color c1 = Color.FromArgb(c, c, c);
                        ImageProcessor.setPixel(data2, j, i, c1);
                    }
                }
                pictureBox01.Image = bmp2;
                bmp2.UnlockBits(data2);
                return;
            }
        }
Exemple #31
0
        public void CleanUp(System.ComponentModel.CancelEventArgs e = null, bool crash = false)
        {
            if (!crash)
            {
                for (int i = 0; i < graphs.Count; i++)
                {
                    UIGraph g = graphs[i];
                    if (g.Modified && !g.ReadOnly)
                    {
                        var result = MessageBox.Show(this, g.GraphName + " has been modified. Do you want to save the changes?", "Save Changes", MessageBoxButton.YesNoCancel);
                        if (result == MessageBoxResult.Yes)
                        {
                            HandleSave(g);
                        }
                        else if (result == MessageBoxResult.Cancel)
                        {
                            if (e != null)
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                    }
                }
            }

            recent.Save();

            //release all opengl content
            foreach (UIGraph g in graphs)
            {
                if (crash)
                {
                    if (!string.IsNullOrEmpty(g.FilePath))
                    {
                        if (g.FromArchive)
                        {
                            if (string.IsNullOrEmpty(g.FromArchivePath))
                            {
                                g.Save(g.FilePath + ".recovery.mtga", true);
                            }
                            else
                            {
                                g.Save(g.FromArchivePath + ".recovery.mtga", true);
                            }
                        }
                        else
                        {
                            g.Save(g.FilePath + ".recovery.mtg", true);
                        }
                    }
                }

                g.DeleteTempArchiveData();
                g.Release();
            }

            graphs.Clear();

            FontManager.Release();

            //clear material and shader caches
            PBRMaterial.ReleaseBRDF();
            ImageProcessor.ReleaseAll();
            Material.Material.ReleaseAll();

            //release gl view
            if (UI3DPreview.Instance != null)
            {
                UI3DPreview.Instance.Release();
            }

            if (UIPreviewPane.Instance != null)
            {
                UIPreviewPane.Instance.Release();
            }

            ViewContext.Dispose();
        }
        /// <summary>
        /// 画像に処理を行う。
        /// </summary>
        /// <param name="buffer">画像バッファ</param>
        /// <returns>処理結果が返る</returns>
        public override ImageBuffer Process(ImageBuffer buffer)
        {
            ImageBuffer dstImage = ImageBuffer.Create(buffer.Width * 2, buffer.Height * 2);

            // まずオリジナルと同じにできるところを生成する。
            for (int y = 0; y < dstImage.Height; y += 2)
            {
                for (int x = 0; x < dstImage.Width; x += 2)
                {
                    dstImage.SetPixel(x, y, buffer.GetPixel((x >> 1), (y >> 1)));
                }
            }

            // ここからエンプティなところを埋めてくんだけど。
            // 実は結構面倒だし、タイルになってたらうまくいかんのだよね。ごふっ

            // オリジナルのところの右トナリ
            for (int y = 0; y < dstImage.Height; y += 2)
            {
                for (int x = 1; x < dstImage.Width; x += 2)
                {
                    int   srcX = (x - 1) >> 1;
                    int   srcY = y >> 1;
                    Color src1 = buffer.GetPixel(srcX, srcY);
                    Color src2 = buffer.GetPixel(srcX + 1, srcY);
                    if ((src1.A == 0) || (src2.A == 0))
                    {
                        // どっちか透明なら無色にする。
                    }
                    else
                    {
                        // 両方色ついてるなら混合色を作る
                        Color c = ImageProcessor.Blend(src1, src2);
                        dstImage.SetPixel(x, y, c);
                    }
                }
            }

            // オリジナルのところの1つ下
            for (int y = 1; y < dstImage.Height; y += 2)
            {
                for (int x = 0; x < dstImage.Width; x += 2)
                {
                    int   srcX = x >> 1;
                    int   srcY = (y - 1) >> 1;
                    Color src1 = buffer.GetPixel(srcX, srcY);
                    Color src2 = buffer.GetPixel(srcX, srcY + 1);
                    if ((src1.A == 0) || (src2.A == 0))
                    {
                        // どっちか透明なら無色にする。
                    }
                    else
                    {
                        // 両方色ついてるなら混合色を作る
                        Color c = ImageProcessor.Blend(src1, src2);
                        dstImage.SetPixel(x, y, c);
                    }
                }
            }

            // オリジナルのところの右下
            for (int y = 1; y < dstImage.Height; y += 2)
            {
                for (int x = 1; x < dstImage.Width; x += 2)
                {
                    Color c1 = dstImage.GetPixel(x - 1, y);
                    Color c2 = dstImage.GetPixel(x + 1, y);
                    Color c3 = dstImage.GetPixel(x, y - 1);
                    Color c4 = dstImage.GetPixel(x, y + 1);

                    if (((c1.A != 0) && (c2.A != 0)) || ((c3.A != 0) && (c4.A != 0)))
                    {
                        // 対角のどちらかが色つき
                        // Note:
                        // 斜め対角は右トナリ、左トナリの判定結果が
                        // c1, c2, c3, c4に効き、この判定で処理できる
                        Color c12   = ImageProcessor.Blend(c1, c2);
                        Color c34   = ImageProcessor.Blend(c3, c4);
                        Color c1234 = ImageProcessor.Blend(c12, c34);

                        dstImage.SetPixel(x, y, c1234);
                    }
                }
            }

            return(dstImage);
        }
 public ImageProcessorService(IFeatureManager featureManager, IOptions <ImageProcessor> imageProcessor)
 {
     _featureManager = featureManager;
     _imageProcessor = imageProcessor.Value;
 }
Exemple #34
0
        static void ProcessFile(string[] args)
        {
            try
            {
                _filePath = args[0];
                if (!File.Exists(_filePath))
                {
                    Console.WriteLine("指定的文件不存在!");
                }
                else
                {
                    _fileDir     = new FileInfo(_filePath).DirectoryName;
                    _fileContent = File.ReadAllText(_filePath);
                    var imgProcessor = new ImageProcessor();
                    var imgList      = imgProcessor.Process(_fileContent);
                    Console.WriteLine($"提取图片成功,共{imgList.Count}个.");

                    //循环上传图片
                    foreach (var img in imgList)
                    {
                        if (img.StartsWith("http"))
                        {
                            Console.WriteLine($"{img} 跳过.");
                            continue;
                        }

                        try
                        {
                            string imgPhyPath = Path.Combine(_fileDir, img);
                            if (File.Exists(imgPhyPath))
                            {
                                var imgUrl = ImageUploader.Upload(imgPhyPath);
                                if (!ReplaceDic.ContainsKey(img))
                                {
                                    ReplaceDic.Add(img, imgUrl);
                                }
                                Console.WriteLine($"{img} 上传成功. {imgUrl}");
                            }
                            else
                            {
                                Console.WriteLine($"{img} 未发现文件.");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }

                    //替换
                    foreach (var key in ReplaceDic.Keys)
                    {
                        _fileContent = _fileContent.Replace(key, ReplaceDic[key]);
                    }

                    string newFileName = _filePath.Substring(0, _filePath.LastIndexOf('.')) + "-cnblog" +
                                         new FileInfo(_filePath).Extension;
                    File.WriteAllText(newFileName, _fileContent, EncodingType.GetType(_filePath));

                    Console.WriteLine($"处理完成!文件保存在:{newFileName}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        private void Init()
        {
            if (h.thumb == null)
            {
                h.thumb = ImageProcessor.FromResource("NoImage.jpg");
            }
            thumbNail.Source       = h.thumb;
            thumbBrush.ImageSource = h.thumb;
            thumbNail.ToolTip      = GetToolTip(panel.Height);

            authorsPanel.Children.Clear();
            authorsPanel.Children.Add(new Label {
                Content = "작가 :"
            });
            tagPanel.Children.Clear();
#pragma warning disable CS0618 // 형식 또는 멤버는 사용되지 않습니다.
            if (blur)
            {
                thumbNail.BitmapEffect = new BlurBitmapEffect {
                    Radius = 5, KernelType = KernelType.Gaussian
                }
            }
            ;
            Config config = new Config();
            config.Load();
            if (config.ArrayValue <string>(Settings.except_tags).Any(x => h.tags.Select(y => y.name).Contains(x)))
            {
                if (config.BoolValue(Settings.block_tags) ?? false)
                {
                    MainWindow.MainPanel.Children.Remove(this);
                    return;
                }
                else
                {
                    thumbNail.BitmapEffect = new BlurBitmapEffect {
                        Radius = 5, KernelType = KernelType.Gaussian
                    }
                };
            }
#pragma warning restore CS0618 // 형식 또는 멤버는 사용되지 않습니다.

            pageLabel.Content = h.page + "p";

            int    GB         = 1024 * 1024 * 1024;
            int    MB         = 1024 * 1024;
            int    KB         = 1024;
            double FolderByte = h.FolderByte;
            sizeLabel.Content = Math.Round(FolderByte, 2) + "B";
            if (FolderByte > KB)
            {
                sizeLabel.Content = Math.Round(FolderByte / KB, 2) + "KB";
            }
            if (FolderByte > MB)
            {
                sizeLabel.Content = Math.Round(FolderByte / MB, 2) + "MB";
            }
            if (FolderByte > GB)
            {
                sizeLabel.Content = Math.Round(FolderByte / GB, 2) + "GB";
            }

            double SizePerPage = h.SizePerPage;
            sizeperpageLabel.Content = Math.Round(SizePerPage, 2) + "B";
            if (SizePerPage > KB)
            {
                sizeperpageLabel.Content = Math.Round(SizePerPage / KB, 2) + "KB";
            }
            if (SizePerPage > MB)
            {
                sizeperpageLabel.Content = Math.Round(SizePerPage / MB, 2) + "MB";
            }
            if (SizePerPage > GB)
            {
                sizeperpageLabel.Content = Math.Round(SizePerPage / GB, 2) + "GB";
            }

            ChangeColor(this);
            HitomiInfo hInfo = null;
            Uri        uriResult;
            bool       result = Uri.TryCreate(h.dir, UriKind.Absolute, out uriResult) &&
                                ((uriResult.Scheme == Uri.UriSchemeHttp) || (uriResult.Scheme == Uri.UriSchemeHttps));
            if (h.tags.Count > 0)
            {
                foreach (Tag tag in h.tags)
                {
                    tag tag1 = new tag
                    {
                        TagType = tag.types,
                        TagName = tag.name
                    };
                    switch (tag.types)
                    {
                    case Structs.Tag.Types.female:
                        tag1.TagColor = new SolidColorBrush(Color.FromRgb(255, 94, 94));
                        break;

                    case Structs.Tag.Types.male:
                        tag1.TagColor = new SolidColorBrush(Color.FromRgb(65, 149, 244));
                        break;

                    case Structs.Tag.Types.tag:
                    default:
                        tag1.TagColor = new SolidColorBrush(Color.FromRgb(153, 153, 153));
                        break;
                    }
                    tagPanel.Children.Add(tag1);
                }
            }
            else if (result)
            {
            }
            else if (File.Exists(System.IO.Path.Combine(h.dir, "info.json")))
            {
                JObject jobject = JObject.Parse(File.ReadAllText(System.IO.Path.Combine(h.dir, "info.json")));

                h.id   = jobject.StringValue("id");
                h.name = jobject.StringValue("name");
                HitomiInfoOrg hInfoOrg = new HitomiInfoOrg();
                foreach (JToken tags in jobject["tags"])
                {
                    tag tag = new tag();
                    tag.TagType = (Tag.Types) int.Parse(tags["types"].ToString());
                    tag.TagName = tags["name"].ToString();
                    switch (tag.TagType)
                    {
                    case Structs.Tag.Types.female:
                        tag.TagColor = new SolidColorBrush(Color.FromRgb(255, 94, 94));
                        break;

                    case Structs.Tag.Types.male:
                        tag.TagColor = new SolidColorBrush(Color.FromRgb(65, 149, 244));
                        break;

                    case Structs.Tag.Types.tag:
                    default:
                        tag.TagColor = new SolidColorBrush(Color.FromRgb(153, 153, 153));
                        break;
                    }
                    tagPanel.Children.Add(tag);
                }
                ftype = (Hitomi.Type) int.Parse(jobject["type"].ToString());
                if (jobject.ContainsKey("authors"))
                {
                    h.authors = jobject["authors"].Select(x => x.ToString()).ToArray();
                }
                else if (jobject.ContainsKey("author"))
                {
                    h.authors = jobject["author"].ToString().Split(new string[] { ", " }, StringSplitOptions.None);
                }
                else
                {
                    h.authors = new string[0];
                }
            }
            else if (File.Exists(System.IO.Path.Combine(h.dir, "info.txt")))
            {
                HitomiInfoOrg hitomiInfoOrg = new HitomiInfoOrg();
                string[]      lines         = File.ReadAllLines(System.IO.Path.Combine(h.dir, "info.txt")).Where(x => x.Length > 0).ToArray();
                foreach (string line in lines)
                {
                    if (line.StartsWith("태그: "))
                    {
                        hitomiInfoOrg.Tags = line.Remove(0, "태그: ".Length);
                    }
                    if (line.StartsWith("작가: "))
                    {
                        hitomiInfoOrg.Author = line.Remove(0, "작가: ".Length);
                    }
                    if (line.StartsWith("갤러리 넘버: "))
                    {
                        hitomiInfoOrg.Number = line.Remove(0, "갤러리 넘버: ".Length);
                    }
                    if (line.StartsWith("제목: "))
                    {
                        hitomiInfoOrg.Title = line.Remove(0, "제목: ".Length);
                    }
                }
                hInfo     = HitomiInfo.Parse(hitomiInfoOrg);
                h.name    = hInfo.Title;
                h.id      = hInfo.Number.ToString();
                h.author  = hInfo.Author;
                h.authors = hInfo.Author.Split(new string[] { ", " }, StringSplitOptions.None);
                foreach (Tag tag in hInfo.Tags)
                {
                    tag tag1 = new tag
                    {
                        TagType = tag.types,
                        TagName = tag.name
                    };
                    switch (tag.types)
                    {
                    case Structs.Tag.Types.female:
                        tag1.TagColor = new SolidColorBrush(Color.FromRgb(255, 94, 94));
                        break;

                    case Structs.Tag.Types.male:
                        tag1.TagColor = new SolidColorBrush(Color.FromRgb(65, 149, 244));
                        break;

                    case Structs.Tag.Types.tag:
                    default:
                        tag1.TagColor = new SolidColorBrush(Color.FromRgb(153, 153, 153));
                        break;
                    }
                    tagPanel.Children.Add(tag1);
                }
            }
            else
            {
                h.authors = new string[0];
            }

            if (large)
            {
                panel.Height = 150;
                authorsStackPanel.Visibility = Visibility.Visible;
                foreach (string artist in h.authors)
                {
                    if (h.authors.ToList().IndexOf(artist) != 0)
                    {
                        Label dot = new Label();
                        dot.Content = ", ";
                        dot.Padding = new Thickness(0, 5, 2.5, 5);
                        authorsPanel.Children.Add(dot);
                    }
                    Label lb = new Label();
                    lb.Content    = artist;
                    lb.Foreground = new SolidColorBrush(Colors.Blue);
                    lb.Cursor     = Cursors.Hand;
                    lb.MouseDown += authorLabel_MouseDown;
                    lb.Padding    = new Thickness(0, 5, 0, 5);
                    authorsPanel.Children.Add(lb);
                }
            }

            nameLabel.Width   = panel.Width - border.Width;
            nameLabel.Content = h.name;
            ContextSetup();
        }
Exemple #36
0
            public void SaveImage(MultipartParser parser)
            {
                ImageProcessor processor = new ImageProcessor(parser);

                File.WriteAllBytes(Resources.BasePath + "/resources/images/users/User" + this.id + Resources.ImageFormat, processor.Data);
            }
Exemple #37
0
            public override void paint(Graphics g, bool drawHandles, ViewParameters parameters)
            {
                if (pic.sp.chkUseShadow.Checked || pic.sp.chkUseBorder.Checked)
                {
                    Brush b         = shape.ShapeBrush;
                    float thickness = scaledThickness(shape, parameters);
                    Pen   pen       = new Pen(b, thickness);

                    RectangleF r = getShapeRectangle(shape.Handles["start"], shape.Handles["end"], parameters);
                    r.Inflate(thickness / 2, thickness / 2);
                    if (pic.sp.chkUseShadow.Checked && pic.sp.chkUseBorder.Checked)
                    {
                        Pen shadowPen = new Pen(Constants.SHADOW_COLOR, thickness);
                        g.DrawRectangle(
                            shadowPen,
                            r.X + Constants.SHADOW_X * parameters.ZoomRatio,
                            r.Y + Constants.SHADOW_Y * parameters.ZoomRatio,
                            r.Width, r.Height);
                        shadowPen.Dispose();
                    }
                    if (pic.sp.chkUseBorder.Checked)
                    {
                        g.DrawRectangle(pen, r.Left, r.Top, r.Width, r.Height);
                    }
                }
                if (pic == null || pic.Img == null)
                {
                    return;
                }

                Point      ps   = parameters.toAbsolute(pic.Handles["start"]);
                Point      pe   = parameters.toAbsolute(pic.Handles["end"]);
                RectangleF rect = getShapeRectangleF(ps, pe);
                float      x    = Math.Min(ps.X, pe.X);
                float      y    = Math.Min(ps.Y, pe.Y);

                PointF[] dest = new PointF[3];
                dest[0] = new PointF(x, y);
                dest[1] = new PointF(x + rect.Width, y);
                dest[2] = new PointF(x, y + rect.Height);
                if (pic.Highlight && UseHilights)
                {
                    Bitmap   copy = new Bitmap(pic.Img.Width, pic.Img.Height);
                    Graphics gg   = Graphics.FromImage(copy);
                    gg.DrawImageUnscaled(pic.Img, 0, 0);
                    ImageProcessor.Invert(copy);
                    g.DrawImage(copy, dest);
                    copy.Dispose();
                }
                else
                {
                    if (pic.sp.radioOriginal.Checked && parameters.ZoomRatio == 1)
                    {
                        g.DrawImageUnscaled(pic.Img, (int)x, (int)y);
                    }
                    else
                    {
                        g.DrawImage(pic.Img, dest);
                    }
                }
                base.paint(g, drawHandles && !pic.sp.radioOriginal.Checked, parameters);
            }
Exemple #38
0
 public void SobelYFilter32BitTest()
 {
     double[] kernel = { -1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0 };
     ImageProcessor.Filter(WorkingDirectory + "test32.bmp", WorkingDirectory + "ResultsOfNewProgram/sobely32.bmp", kernel);
     FileAssert.AreEqual(WorkingDirectory + "ResultsOfNewProgram/sobely32.bmp", WorkingDirectory + "ResultsOfLastProgram/sobely32.bmp");
 }
 public void TestInit()
 {
     _imageProcessor = new ImageProcessor();
     _sourceImage    = new Bitmap(_imagePath);
 }
Exemple #40
0
 public void AveragingFilter24BitTest()
 {
     double[] kernel = { 1.0 / 9, 1.0 / 9, 1.0 / 9, 1.0 / 9, 1.0 / 9, 1.0 / 9, 1.0 / 9, 1.0 / 9, 1.0 / 9 };
     ImageProcessor.Filter(WorkingDirectory + "test24.bmp", WorkingDirectory + "ResultsOfNewProgram/averaging24.bmp", kernel);
     FileAssert.AreEqual(WorkingDirectory + "ResultsOfNewProgram/averaging24.bmp", WorkingDirectory + "ResultsOfLastProgram/averaging24.bmp");
 }
Exemple #41
0
 public CreateModel(ApplicationContext context, IHostingEnvironment appEnvironment, IStorageOperations storage)
 {
     _context        = context;
     _appEnvironment = appEnvironment;
     _processor      = new ImageProcessor(storage);
 }
Exemple #42
0
 public DeleteModel(ApplicationContext context, IOptions <Constants> config, IStorageOperations storage)
 {
     _context   = context;
     _config    = config;
     _processor = new ImageProcessor(storage);
 }
 public void Initialize()
 {
     _testee = new ImageProcessor();
 }
        /// <summary>
        /// Registers resources that classes will depend on
        /// </summary>
        /// <returns>Task.</returns>
        protected override async Task RegisterResources(IProgress <double> progress)
        {
            await base.RegisterResources(progress).ConfigureAwait(false);

            RegisterSingleInstance <IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer));

            RegisterSingleInstance <IServerApplicationHost>(this);
            RegisterSingleInstance <IServerApplicationPaths>(ApplicationPaths);

            RegisterSingleInstance(ServerConfigurationManager);

            LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer);
            RegisterSingleInstance(LocalizationManager);

            RegisterSingleInstance <IBlurayExaminer>(() => new BdInfoExaminer());

            UserDataManager = new UserDataManager(LogManager);
            RegisterSingleInstance(UserDataManager);

            UserRepository = await GetUserRepository().ConfigureAwait(false);

            RegisterSingleInstance(UserRepository);

            DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
            RegisterSingleInstance(DisplayPreferencesRepository);

            ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
            RegisterSingleInstance(ItemRepository);

            ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
            RegisterSingleInstance(ProviderRepository);

            FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);

            RegisterSingleInstance(FileOrganizationRepository);

            AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);

            RegisterSingleInstance(AuthenticationRepository);

            //SyncRepository = await GetSyncRepository().ConfigureAwait(false);
            //RegisterSingleInstance(SyncRepository);

            UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager);
            RegisterSingleInstance(UserManager);

            LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
            RegisterSingleInstance(LibraryManager);

            var musicManager = new MusicManager(LibraryManager);

            RegisterSingleInstance <IMusicManager>(new MusicManager(LibraryManager));

            LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
            RegisterSingleInstance(LibraryMonitor);

            ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
            RegisterSingleInstance(ProviderManager);

            SeriesOrderManager = new SeriesOrderManager();
            RegisterSingleInstance(SeriesOrderManager);

            RegisterSingleInstance <ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));

            HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html", _supportsNativeWebSocket);
            RegisterSingleInstance(HttpServer, false);
            progress.Report(10);

            ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
            RegisterSingleInstance(ServerManager);

            var innerProgress = new ActionableProgress <double>();

            innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));

            await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);

            progress.Report(90);

            ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder);
            RegisterSingleInstance(ImageProcessor);

            SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"));
            RegisterSingleInstance(SyncManager);

            DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager);
            RegisterSingleInstance(DtoService);

            var encryptionManager = new EncryptionManager();

            RegisterSingleInstance <IEncryptionManager>(encryptionManager);

            ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager);
            RegisterSingleInstance(ConnectManager);

            DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer), UserManager, FileSystemManager, LibraryMonitor, ConfigurationManager, LogManager.GetLogger("DeviceManager"));
            RegisterSingleInstance(DeviceManager);

            SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager);
            RegisterSingleInstance(SessionManager);

            var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);

            RegisterSingleInstance <INewsService>(newsService);

            var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);

            RegisterSingleInstance <IFileOrganizationService>(fileOrganizationService);

            progress.Report(15);

            ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient);
            RegisterSingleInstance(ChannelManager);

            TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager);
            RegisterSingleInstance(TVSeriesManager);

            var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);

            RegisterSingleInstance <IAppThemeManager>(appThemeManager);

            var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer);

            RegisterSingleInstance <IDlnaManager>(dlnaManager);

            var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient);

            RegisterSingleInstance <IConnectionManager>(connectionManager);

            CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"));
            RegisterSingleInstance(CollectionManager);

            var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager);

            RegisterSingleInstance <IPlaylistManager>(playlistManager);

            LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer);
            RegisterSingleInstance(LiveTvManager);

            UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager);
            RegisterSingleInstance(UserViewManager);

            var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager);

            RegisterSingleInstance <IContentDirectory>(contentDirectory);

            NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
            RegisterSingleInstance(NotificationManager);

            SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository);
            RegisterSingleInstance(SubtitleManager);

            ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
            RegisterSingleInstance(ChapterManager);

            EncodingManager = new EncodingManager(FileSystemManager, Logger,
                                                  MediaEncoder, ChapterManager);
            RegisterSingleInstance(EncodingManager);

            var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);

            RegisterSingleInstance(activityLogRepo);
            RegisterSingleInstance <IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));

            var authContext = new AuthorizationContext();

            RegisterSingleInstance <IAuthorizationContext>(authContext);
            RegisterSingleInstance <ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
            RegisterSingleInstance <IAuthService>(new AuthService(UserManager, SessionManager, authContext, ServerConfigurationManager));

            RegisterSingleInstance <ISubtitleEncoder>(new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer));

            var displayPreferencesTask = Task.Run(async() => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
            var itemsTask    = Task.Run(async() => await ConfigureItemRepositories().ConfigureAwait(false));
            var userdataTask = Task.Run(async() => await ConfigureUserDataRepositories().ConfigureAwait(false));

            await ConfigureNotificationsRepository().ConfigureAwait(false);

            progress.Report(92);

            await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);

            progress.Report(100);

            SetStaticProperties();

            await((UserManager)UserManager).Initialize().ConfigureAwait(false);

            SetKernelProperties();
        }
        public void RecomposeWithSafeCode()
        {
            using (var originalImage = new Bitmap(OneStepFileName))
            {
                WaveletTransform transform = new InverseWaveletTransform(1);
                ColorChannels channels = new SafeColorChannels(originalImage.Width, originalImage.Height);
                var imageProcessor = new ImageProcessor(channels, transform);
                imageProcessor.ApplyTransform(originalImage);

                VerifyAsImage(originalImage);
            }
        }