コード例 #1
0
        public async Task <IActionResult> UploadImage(IFormFile file, [FromForm] string name, [FromForm] string tags)
        {
            if (file == null)
            {
                file = Request.Form.Files[0];
            }
            ImageOutput output = new ImageOutput();

            if (file != null)
            {
                if (file.Length > 0)
                {
                    //验证是否是图片
                    if (ImageValidation.IsCheck(file))
                    {
                        ImageInput input = new ImageInput();
                        input.File = file;
                        input.Name = name;
                        input.Tags = tags;
                        ImageHandleService handleService = new ImageHandleService();
                        //处理图片
                        output = await handleService.Processing(input, Request);

                        return(Ok(output));
                    }
                }
            }
            return(BadRequest("图片上传失败!"));
        }
コード例 #2
0
        public void GivenAThreeByThreeInputAndATwoByTwoFilter_WhenTheFilterIsSlid_ItShouldReturnAMappedRepresentationOfTheNextSection()
        {
            StrideBasedSlideRetrievalStrategy strategy = new StrideBasedSlideRetrievalStrategy();

            Position position = new Position(0, 0, 1);

            double[,] matrix = new double[4, 4];
            matrix[0, 0]     = 0;
            matrix[0, 1]     = 1;
            matrix[0, 2]     = 2;
            matrix[1, 0]     = 3;
            matrix[1, 1]     = 4;
            matrix[1, 2]     = 5;
            matrix[2, 0]     = 6;
            matrix[2, 1]     = 7;
            matrix[2, 2]     = 8;

            ImageInput input = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            input.SetNumericRepresentation(matrix);

            Slider slider = new Slider(position, 2, 2, 4, true);

            double[] slide    = strategy.GetSlide(input, slider);
            double[] expected = { 0, 1, 3, 4 };

            Assert.IsTrue(Enumerable.SequenceEqual(expected, slide));
        }
        public void GivenAFourByFourInputAndATwoByTwoFilter_WhenTheNeuronIsActivated_ItShouldReturnAFeatureMap()
        {
            FeatureMapNeuronActivationStrategy strategy = new FeatureMapNeuronActivationStrategy(MockDotProduct(), new Configuration());

            double[,] matrix = new double[3, 3];
            matrix[0, 0]     = 0;
            matrix[0, 1]     = 1;
            matrix[0, 2]     = 2;
            matrix[1, 0]     = 3;
            matrix[1, 1]     = 4;
            matrix[1, 2]     = 5;
            matrix[2, 0]     = 6;
            matrix[2, 1]     = 7;
            matrix[2, 2]     = 8;

            ImageInput input = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            input.SetNumericRepresentation(matrix);

            double[] mockFilter = new double[4];

            double[] featureMap = strategy.Activate(input, mockFilter);
            double[] expected   = { 0.3, 2.7, 6.2, 1.9 };

            Assert.IsTrue(Enumerable.SequenceEqual(expected, featureMap));
        }
        public void GivenAnInputSubsectionAndAFilter_WhenAFeatureMapPartIsCalculated_ItShouldCallTheDotProductConvoluteFunction()
        {
            double[,] inputSubsection = new double[3, 3];
            inputSubsection[0, 0]     = 0;
            inputSubsection[0, 1]     = 1;
            inputSubsection[1, 0]     = 2;
            inputSubsection[1, 1]     = 4;

            double[] filter = { 0.1, 0.2 };

            ImageInput input = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            input.SetNumericRepresentation(inputSubsection);

            Mock <IDotProductConvolutionStrategy> dotProductMock = new Mock <IDotProductConvolutionStrategy>();

            dotProductMock.SetupSequence(x => x.Calculate(It.IsAny <double[]>(), It.IsAny <double[]>()))
            .Returns(0.3).Returns(2.7)
            .Returns(6.2).Returns(1.9)
            .Returns(3.4).Returns(0.8);

            FeatureMapNeuronActivationStrategy strategy = new FeatureMapNeuronActivationStrategy(dotProductMock.Object, new Configuration());

            double part = strategy.ConvolveSubSection(input.GetNumericRepresentation(), filter);

            dotProductMock.Verify(c => c.Calculate(It.IsAny <double[]>(), It.IsAny <double[]>()), Times.Exactly(1));
        }
コード例 #5
0
        public void GivenAFourByFourInputAndATwoByTwoFilter_WhenTheFilterIsSlidFromTheEnd_ItShouldReturnARepresentationOfTheLeftestSectionOneLevelDown()
        {
            StrideBasedSlideRetrievalStrategy strategy = new StrideBasedSlideRetrievalStrategy();

            Position position = new Position(2, 0, 1);

            double[,] matrix = new double[4, 4];
            matrix[0, 0]     = 0;
            matrix[0, 1]     = 1;
            matrix[0, 2]     = 2;
            matrix[0, 3]     = 3;
            matrix[1, 0]     = 4;
            matrix[1, 1]     = 5;
            matrix[1, 2]     = 6;
            matrix[1, 3]     = 7;
            matrix[2, 0]     = 8;
            matrix[2, 1]     = 9;
            matrix[2, 2]     = 10;
            matrix[2, 3]     = 11;
            matrix[3, 0]     = 12;
            matrix[3, 1]     = 13;
            matrix[3, 2]     = 14;
            matrix[3, 3]     = 15;

            ImageInput input = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            input.SetNumericRepresentation(matrix);

            Slider slider = new Slider(position, 2, 2, 4, true);

            double[] slide    = strategy.GetSlide(input, slider);
            double[] expected = { 2, 3, 6, 7 };

            Assert.IsTrue(Enumerable.SequenceEqual(expected, slide));
        }
コード例 #6
0
        public void GivenAnIImageInput_WhenTheImageInputIsSplit_ItShouldReturnAListOfSmallerImageInputs()
        {
            Mock <IConfiguration> config = new Mock <IConfiguration>();

            config.Setup(x => x.GetValue(It.IsAny <string>())).Returns("2");

            ImageInput imageInput = new ImageInput(new TwoDimensionalMapper(), config.Object);

            double[,] matrix = new double[4, 4];
            matrix[0, 0]     = 0;
            matrix[0, 1]     = 1;
            matrix[0, 2]     = 2;
            matrix[0, 3]     = 3;
            matrix[1, 0]     = 4;
            matrix[1, 1]     = 5;
            matrix[1, 2]     = 6;
            matrix[1, 3]     = 7;
            matrix[2, 0]     = 8;
            matrix[2, 1]     = 9;
            matrix[2, 2]     = 10;
            matrix[2, 3]     = 11;
            matrix[3, 0]     = 12;
            matrix[3, 1]     = 13;
            matrix[3, 2]     = 14;
            matrix[3, 3]     = 15;

            imageInput.SetNumericRepresentation(matrix);

            List <double[]> result = imageInput.GetSplitSubsections();

            Assert.IsTrue(result[0].SequenceEqual(new double[] { 0, 1, 4, 5 }));
            Assert.IsTrue(result[1].SequenceEqual(new double[] { 2, 3, 6, 7 }));
            Assert.IsTrue(result[2].SequenceEqual(new double[] { 8, 9, 12, 13 }));
            Assert.IsTrue(result[3].SequenceEqual(new double[] { 10, 11, 14, 15 }));
        }
コード例 #7
0
        public IActionResult PostImage(ImageInput image)
        {
            var imageProduct = new ImageMv();

            imageProduct.CreateBy  = Guid.Parse("a845b16a-4ca6-48e2-4ca6-08d817450c1a");
            imageProduct.ProductId = image.ProductId;
            //convert to image to base 64
            var ms = new MemoryStream();

            image.FileInput.CopyTo(ms);
            var    fileBytes = ms.ToArray();
            string s         = Convert.ToBase64String(fileBytes);

            imageProduct.FileInput = s;

            if (ImageBus.PostImage(imageProduct).Result)
            {
                TempData[ConstKey.Success] = "Add Success!";
            }
            else
            {
                TempData[ConstKey.Error] = "Fail, Try again !";
            }
            return(RedirectToAction("ForProduct", "ImageProduct", new { productId = image.ProductId }));
        }
コード例 #8
0
ファイル: MainWindow.xaml.cs プロジェクト: r0mk1n/LedBadge
 private void SendImage(object sender, RoutedEventArgs e)
 {
     foreach (string path in ImageInput.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
     {
         m_vm.ImageProvider.SendImage(path);
     }
     ImageInput.Clear();
 }
コード例 #9
0
 private void TemplateSet_Load(object sender, EventArgs e)
 {
     if (!ReferenceEquals(m_imageInput, null))
     {
         aqDisplayCreateModel.Image = ImageInput.Clone() as Bitmap;
         aqDisplayCreateModel.FitToScreen();
         aqDisplayCreateModel.Update();
     }
 }
コード例 #10
0
        public void GivenAnIImageInputIsInitialised_WhenThePositionIsRetrieved_ItShouldUseTheMapperToReturnAnArrayRepresentation()
        {
            Mock <ITwoDimensionalMapper> mapperMock = new Mock <ITwoDimensionalMapper>();

            ImageInput imageInput = new ImageInput(mapperMock.Object, new Configuration());

            double[] result = imageInput.GetNumericRepresentation();

            mapperMock.Verify(c => c.GetArrayRepresentation(It.IsAny <double[, ]>()), Times.Exactly(1));
        }
コード例 #11
0
        public List <double[]> Convolve(ImageInput imageSubsection, List <double[]> filters)
        {
            List <double[]> featureMaps = new List <double[]>();

            foreach (double[] filter in filters)
            {
                featureMaps.Add(neuronActivationStrategy.Activate(imageSubsection, filter));
            }

            return(featureMaps);
        }
コード例 #12
0
        public IActionResult UploadImageCad(ImageInput imageInput)
        {
            if (ModelState.IsValid)
            {
                var CurrentDate       = DateTime.Now;
                var UploadDate        = CurrentDate.ToString("yyyyMMdd_hhmmss");
                var userfileName      = User.Identity.Name.ToString();
                var RootFolder        = _hostingEnvironment.WebRootPath;
                var UsersFileLocation = "UsersDirectory";
                //var RootFfolderString = "wwwroot";
                var DxfFileExtension = ".dxf";

                var UserDirectory = $"{_hostingEnvironment.WebRootPath}/{UsersFileLocation}/{userfileName}/{UploadDate}";
                //var UserFilesDirectoryRelative = $"{RootFfolderString}/{UsersFileLocation}/{userfileName}/{UploadDate}";
                var UserFilesDirectoryRelative = $"{UsersFileLocation}/{userfileName}/{UploadDate}";
                //   var ImageFileLocationPaths = new List<String>();
                var uploads = Path.Combine(RootFolder, UsersFileLocation, userfileName, UploadDate);
                //Check if user Directory exsists , if not creates new directory
                var exsits = Directory.Exists(UserDirectory);
                if (!exsits)
                {
                    Directory.CreateDirectory(UserDirectory);
                }

                var filePathName  = ContentDispositionHeaderValue.Parse(imageInput.ImageFile.ContentDisposition).FileName.Trim('"');
                var fileExtention = Path.GetExtension(filePathName);
                if (!(fileExtention == ".jpg" || fileExtention == ".JPG" || fileExtention == ".PNG" || fileExtention == ".png"))
                {
                    return(RedirectToAction("ErrorPage"));
                }
                var fileName     = Guid.NewGuid().ToString("N").Substring(0, 10);
                var FileNameFull = fileName + fileExtention;
                var StaticPath   = Path.Combine(uploads, FileNameFull);
                var StaticPathNameNoExtension = Path.Combine(uploads, fileName);
                var RelativePaths             = $"{UserFilesDirectoryRelative}/{fileName}" + $"{fileExtention}";
                //the image will be saved with a unique filename
                FileStream DestinationStream = new FileStream(StaticPath, FileMode.CreateNew);
                imageInput.ImageFile.CopyTo(DestinationStream);
                var DxfFileName       = Guid.NewGuid().ToString("N").Substring(0, 10);
                var DxfFileStaticPath = Path.Combine(uploads, DxfFileName);
                var DxFRelativePaths  = $"{UserFilesDirectoryRelative}/{DxfFileName}" + $"{DxfFileExtension}";
                TempData["DxfFileStaticPath"] = DxfFileStaticPath;
                TempData["DxFRelativePaths"]  = DxFRelativePaths;
                TempData["ImagePath"]         = RelativePaths;
                TempData["StaticImagePath"]   = StaticPath;
                TempData["FileNameFull"]      = FileNameFull;
                return(RedirectToAction("CanvasDrawer"));
            }
            else
            {
                return(View("Error"));
            }
        }
コード例 #13
0
 internal MediaInput(GroupCall groupCall, GroupCall room, TeamsMeeting teamsMeeting, RtmpStream rtmp, SrtStream srt, ParticipantInput participant, CommunicationCallIdentifierModel activePresenter, CommunicationCallIdentifierModel dominantSpeaker, CommunicationCallIdentifierModel screenShare, ImageInput image, MediaInputType?kind)
 {
     GroupCall       = groupCall;
     Room            = room;
     TeamsMeeting    = teamsMeeting;
     Rtmp            = rtmp;
     Srt             = srt;
     Participant     = participant;
     ActivePresenter = activePresenter;
     DominantSpeaker = dominantSpeaker;
     ScreenShare     = screenShare;
     Image           = image;
     Kind            = kind;
 }
コード例 #14
0
        public IActionResult DeleteFile(ImageInput lImage)
        {
            try
            {
                _propertyService.DeleteFiles(lImage.uri);

                return(Ok());
            }
            catch (System.Exception e)
            {
                _logger.LogError(e, "error: {0}", e.Message);
                return(BadRequest());
            }
        }
コード例 #15
0
        public void GivenAnIImageInput_WhenTheImageInputNumericRepresentationIsSet_ItShouldSetTheTotalRows()
        {
            ImageInput imageInput = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            double[,] numericRepresentation = new double[2, 2];
            numericRepresentation[0, 0]     = 1;
            numericRepresentation[0, 1]     = 2;
            numericRepresentation[1, 0]     = 3;
            numericRepresentation[1, 1]     = 4;

            imageInput.SetNumericRepresentation(numericRepresentation);

            Assert.AreEqual(2, imageInput.TotalRows);
        }
コード例 #16
0
        public void GivenAnIImageInput_WhenTheImageInputNumericRepresentationIsSet_ItShouldReturnTheSetDataWhenRetrieved()
        {
            ImageInput imageInput = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            double[,] numericRepresentation = new double[2, 2];
            numericRepresentation[0, 0]     = 1;
            numericRepresentation[0, 1]     = 2;
            numericRepresentation[1, 0]     = 3;
            numericRepresentation[1, 1]     = 4;

            imageInput.SetNumericRepresentation(numericRepresentation);

            double[] result   = imageInput.GetNumericRepresentation();
            double[] expected = { 1, 2, 3, 4 };

            Assert.IsTrue(result.SequenceEqual(expected));
        }
コード例 #17
0
        public void GivenAnImageSubsectionAndThreeFilters_WhenConvolutionOccurs_ItShouldReturinAListOfFeatureMaps()
        {
            Mock <IFeatureMapNeuronActivationStrategy> mock = new Mock <IFeatureMapNeuronActivationStrategy>();

            mock.SetupSequence(x => x.Activate(It.IsAny <ImageInput>(), It.IsAny <double[]>()))
            .Returns(new double[4] {
                0.2, 1.3, 0.8, 3.1
            })
            .Returns(new double[4] {
                0.8, 5.2, 1.1, 1.1
            })
            .Returns(new double[4] {
                0.1, 1.1, 0.5, 0.4
            });

            ImageInput input = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            input.SetNumericRepresentation(new double[4, 4]);

            List <double[]> filters = new List <double[]>()
            {
                new double[2], new double[2], new double[2]
            };

            Convolution     convolution = new Convolution(mock.Object);
            List <double[]> result      = convolution.Convolve(input, filters);

            List <double[]> expectation = new List <double[]>();

            expectation.Add(new double[4] {
                0.2, 1.3, 0.8, 3.1
            });
            expectation.Add(new double[4] {
                0.8, 5.2, 1.1, 1.1
            });
            expectation.Add(new double[4] {
                0.1, 1.1, 0.5, 0.4
            });

            Assert.IsTrue(expectation[0].SequenceEqual(result[0]));
            Assert.IsTrue(expectation[1].SequenceEqual(result[1]));
            Assert.IsTrue(expectation[2].SequenceEqual(result[2]));
        }
コード例 #18
0
        private static string SaveImageOnServer(ImageInput input)
        {
            if (string.IsNullOrEmpty(input?.ImageId) || input.Image == null)
            {
                return(null);
            }


            var dir    = Directory.GetCurrentDirectory();
            var path   = FilesPath + PicturesPath;
            var dbpath = DbFilesPath + PicturesPath;

            var folder    = input.Type == FileType.Jpeg ? PicturesPathJpeg : PicturesPathWebp;
            var extension = input.Type == FileType.Jpeg ? ".jpeg" : ".webp";

            var samePath = folder + "/" + input.ImageId + extension;
            var result   = dbpath + samePath;

            var imagePath = dir + path + samePath;


            if (!Directory.Exists(dir + path))
            {
                Directory.CreateDirectory(dir + path);
            }

            if (!Directory.Exists(dir + path + folder))
            {
                Directory.CreateDirectory(dir + path + folder);
            }

            try
            {
                var img = System.Drawing.Image.FromStream(new MemoryStream(input.Image));
                img.Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch
            {
                return(null);
            }

            return(result);
        }
コード例 #19
0
        public void GivenAnInputSubsectionAndAFilter_WhenAFeatureMapPartIsCalculated_ItShouldReturnTheDotProduct()
        {
            double[,] inputSubsection = new double[3, 3];
            inputSubsection[0, 0]     = 0;
            inputSubsection[0, 1]     = 1;
            inputSubsection[1, 0]     = 2;
            inputSubsection[1, 1]     = 4;

            double[] filter = { 0.1, 0.2 };

            ImageInput input = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            input.SetNumericRepresentation(inputSubsection);

            FeatureMapNeuronActivationStrategy strategy = new FeatureMapNeuronActivationStrategy(MockDotProduct(), new Configuration());

            double part = strategy.ConvolveSubSection(input.GetNumericRepresentation(), filter);

            Assert.AreEqual(0.3, part);
        }
コード例 #20
0
        public double[] GetSlide(ImageInput input, Slider slider)
        {
            int initialIndex     = indexCalculator.GetIndex(input.TotalColumns, slider.Position.X, slider.Position.Y);
            int skipCount        = initialIndex;
            int filterDimensions = slider.SliderWidth * slider.SliderHeight;
            int maximumIndex     = filterDimensions + initialIndex + slider.SliderHeight;

            double[] newSlide = new double[0];

            while (skipCount < maximumIndex)
            {
                newSlide = newSlide.Concat(input.GetNumericRepresentation()
                                           .Select(i => i)
                                           .Skip(skipCount)
                                           .Take(slider.SliderWidth))
                           .ToArray();
                skipCount += input.TotalColumns;
            }

            return(newSlide);
        }
コード例 #21
0
        public async Task <bool> pushImage(ImageInput input)
        {
            var config = this.Configuration.GetSection("Key")["containerName"];

            try
            {
                var blob = blobService.GetBlob("sessionGuid", config);
                if (blob != null)
                {
                    var fileName = input.user.Id + "/" + input.user.Id + "-" + input.sessionGuid + "/" + input.imageName;
                    await blobService.UploadFileBlob(fileName, input.image, config);
                }

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(false);
            }
        }
コード例 #22
0
        public void GivenAFourByFourInputAndAThreeByThreeFilter_WhenTheFilterIsSlid_ItShouldReturnAMappedRepresentationOfTheNextSection()
        {
            Mock <IConfiguration> configuration = new Mock <IConfiguration>();

            configuration.Setup(x => x.GetValue(It.IsAny <String>())).Returns("3");

            StrideBasedSlideRetrievalStrategy strategy = new StrideBasedSlideRetrievalStrategy();

            Position position = new Position(0, 0, 1);

            double[,] matrix = new double[4, 4];
            matrix[0, 0]     = 0;
            matrix[0, 1]     = 1;
            matrix[0, 2]     = 2;
            matrix[0, 3]     = 3;
            matrix[1, 0]     = 4;
            matrix[1, 1]     = 5;
            matrix[1, 2]     = 6;
            matrix[1, 3]     = 7;
            matrix[2, 0]     = 8;
            matrix[2, 1]     = 9;
            matrix[2, 2]     = 10;
            matrix[2, 3]     = 11;
            matrix[3, 0]     = 12;
            matrix[3, 1]     = 13;
            matrix[3, 2]     = 14;
            matrix[3, 3]     = 15;

            ImageInput input = new ImageInput(new TwoDimensionalMapper(), new Configuration());

            input.SetNumericRepresentation(matrix);
            Slider slider = new Slider(position, 3, 3, 4, true);

            double[] slide = strategy.GetSlide(input, slider);

            double[] expected = { 0, 1, 2, 4, 5, 6, 8, 9, 10 };

            Assert.IsTrue(Enumerable.SequenceEqual(expected, slide));
        }
コード例 #23
0
        public async Task <IActionResult> UploadImages(List <IFormFile> files)
        {
            if (files.Count == 0)
            {
                if (Request.Form.Files.Count > 0)
                {
                    foreach (var item in Request.Form.Files)
                    {
                        files.Add(item);
                    }
                }
            }
            if (files.Count > 0)
            {
                List <ImageInput> imageInputs = new List <ImageInput>();
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        //验证是否是图片
                        if (ImageValidation.IsCheck(file))
                        {
                            ImageInput input = new ImageInput();
                            input.File = file;
                            input.Name = file.Name;
                            input.Tags = file.Name;
                            imageInputs.Add(input);
                        }
                    }
                }

                ImageHandleService handleService = new ImageHandleService();
                //处理图片
                var output = await handleService.ProcessingImages(imageInputs, Request);

                return(Ok(output));
            }
            return(BadRequest("图片上传失败!"));
        }
コード例 #24
0
        public double[] Activate(ImageInput input, double[] filter)
        {
            int stride       = Int32.Parse(configuration.GetValue("Stride"));
            int finalIndex   = input.TotalColumns * input.TotalRows;
            int filterWidth  = Int32.Parse(configuration.GetValue("FilterWidth"));
            int filterHeight = Int32.Parse(configuration.GetValue("FilterHeight"));


            Position position = new Position(0, 0, stride);
            Slider   slider   = new Slider(position, filterWidth, filterHeight, input.TotalColumns, true);

            List <Double> featureMap           = new List <double>();
            int           totalFeatureSections = (input.TotalRows - 1) * (input.TotalColumns - 1);

            while (featureMap.Count() < totalFeatureSections)
            {
                slider.Slide();
                double[] slide = this.slidingStrategy.GetSlide(input, slider);
                featureMap.Add(this.ConvolveSubSection(slide, filter));
            }

            return(featureMap.ToArray());
        }
コード例 #25
0
ファイル: SlideController.cs プロジェクト: josdeweger/MVCBlog
        public ActionResult CreateStep2(ImageView model)
        {
            var image = WebImage.GetImageFromRequest();

            if (image != null)
            {
                if (image.Width > 500)
                {
                    image.Resize(500, ((500 * image.Height) / image.Width));
                }

                var filename = Path.GetFileName(image.FileName);
                image.Save(Path.Combine(BlogGlobals.TemporaryImageFolder, filename));
                filename = Path.Combine(BlogGlobals.TemporaryImageFolder, filename);

                model.ImageUrl = Url.Content(filename);

                var imageInput = new ImageInput()
                {
                    Image = model,
                    Width = image.Width,
                    Height = image.Height,

                    Top = image.Height * 0.1,
                    Left = image.Width * 0.9,
                    Right = image.Width * 0.9,
                    Bottom = image.Height * 0.9
                };

                return View("CreateStep2", imageInput);

            }

            return RedirectToAction("CreateStep1");
            //return View("CreateStep1", model);
        }
コード例 #26
0
        private void ImageInput_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            toolTip1.SetToolTip(ImageInput, e.X.ToString() + ", " + e.Y.ToString());
            Pen      ppen = new Pen(mlinecolor, 1);
            Graphics g;

            ImageInput.Refresh();
            try
            {
                g = ImageInput.CreateGraphics();
                Rectangle rec = new Rectangle(e.X, e.Y, (int)(WindowSize * Convert.ToInt32(scalepercentage.Text) / 100), (int)(WindowSize * Convert.ToInt32(scalepercentage.Text) / 100));
                g.DrawRectangle(ppen, rec);
                current.X  = e.X;
                current.Y  = e.Y;
                ppen.Color = Color.Red;
                g.DrawLine(ppen, ImageInput.Width / 2, ImageInput.Top, ImageInput.Width / 2, ImageInput.Height);
                g.DrawLine(ppen, 0, ImageInput.Height / 2, ImageInput.Width, ImageInput.Height / 2);
                ppen.Color = Color.LightBlue;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #27
0
        /// <summary>
        /// This is used by child HighDimensionVisualizer windows
        /// </summary>
        private Tuple<UIElement, VectorInt> GetPreviewImage(ISOMInput input)
        {
            bool showHash = chkVisualizerShowHash.IsChecked.Value;

            ImageInput nodeImage = input as ImageInput;
            if (nodeImage == null)
            {
                // This is probably a node, instead of an input image (the nodes are sent as static control points)
                nodeImage = new ImageInput(null, input.Weights, input.Weights);
                showHash = true;
            }

            return GetPreviewImage(nodeImage, showHash, 80, false, -1);
        }
コード例 #28
0
        internal static MediaInput DeserializeMediaInput(JsonElement element)
        {
            Optional <GroupCall>        groupCall    = default;
            Optional <GroupCall>        room         = default;
            Optional <TeamsMeeting>     teamsMeeting = default;
            Optional <RtmpStream>       rtmp         = default;
            Optional <SrtStream>        srt          = default;
            Optional <ParticipantInput> participant  = default;
            Optional <CommunicationCallIdentifierModel> activePresenter = default;
            Optional <CommunicationCallIdentifierModel> dominantSpeaker = default;
            Optional <CommunicationCallIdentifierModel> screenShare     = default;
            Optional <ImageInput>     image = default;
            Optional <MediaInputType> kind  = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("groupCall"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    groupCall = GroupCall.DeserializeGroupCall(property.Value);
                    continue;
                }
                if (property.NameEquals("room"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    room = GroupCall.DeserializeGroupCall(property.Value);
                    continue;
                }
                if (property.NameEquals("teamsMeeting"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    teamsMeeting = TeamsMeeting.DeserializeTeamsMeeting(property.Value);
                    continue;
                }
                if (property.NameEquals("rtmp"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    rtmp = RtmpStream.DeserializeRtmpStream(property.Value);
                    continue;
                }
                if (property.NameEquals("srt"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    srt = SrtStream.DeserializeSrtStream(property.Value);
                    continue;
                }
                if (property.NameEquals("participant"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    participant = ParticipantInput.DeserializeParticipantInput(property.Value);
                    continue;
                }
                if (property.NameEquals("activePresenter"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    activePresenter = CommunicationCallIdentifierModel.DeserializeCommunicationCallIdentifierModel(property.Value);
                    continue;
                }
                if (property.NameEquals("dominantSpeaker"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    dominantSpeaker = CommunicationCallIdentifierModel.DeserializeCommunicationCallIdentifierModel(property.Value);
                    continue;
                }
                if (property.NameEquals("screenShare"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    screenShare = CommunicationCallIdentifierModel.DeserializeCommunicationCallIdentifierModel(property.Value);
                    continue;
                }
                if (property.NameEquals("image"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    image = ImageInput.DeserializeImageInput(property.Value);
                    continue;
                }
                if (property.NameEquals("kind"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    kind = new MediaInputType(property.Value.GetString());
                    continue;
                }
            }
            return(new MediaInput(groupCall.Value, room.Value, teamsMeeting.Value, rtmp.Value, srt.Value, participant.Value, activePresenter.Value, dominantSpeaker.Value, screenShare.Value, image.Value, Optional.ToNullable(kind)));
        }
コード例 #29
0
 public IEnumerable <FaceFeature> FaceDetect([FromBody] ImageInput model)
 {
     return(faceDetectionModule.DetectFeatures(model.ImageUrl));
 }
コード例 #30
0
        public async Task <IActionResult> UploadImageCad(ImageInput imageInput)
        {
            if (ModelState.IsValid)
            {
                var CurrentDate       = DateTime.Now;
                var UploadDate        = CurrentDate.ToString("yyyyMMdd_hhmmss");
                var userfileName      = User.Identity.Name.ToString();
                var RootFolder        = _hostingEnvironment.WebRootPath;
                var UsersFileLocation = "UsersDirectory";
                var DxfFileExtension  = ".dxf";
                //var RootFfolderString = "wwwroot";

                var UserDirectory = $"{_hostingEnvironment.WebRootPath}/{UsersFileLocation}/{userfileName}/{UploadDate}";
                //var UserFilesDirectoryRelative = $"{RootFfolderString}/{UsersFileLocation}/{userfileName}/{UploadDate}";
                var UserFilesDirectoryRelative = $"{UsersFileLocation}/{userfileName}/{UploadDate}";
                //   var ImageFileLocationPaths = new List<String>();
                var uploads = Path.Combine(RootFolder, UsersFileLocation, userfileName, UploadDate);
                //Check if user Directory exsists , if not creates new directory
                var exsits = Directory.Exists(UserDirectory);
                if (!exsits)
                {
                    Directory.CreateDirectory(UserDirectory);
                }

                var filePathName  = ContentDispositionHeaderValue.Parse(imageInput.ImageFile.ContentDisposition).FileName.Trim('"');
                var fileExtention = Path.GetExtension(filePathName);
                if (!(fileExtention == ".jpg" || fileExtention == ".JPG" || fileExtention == ".PNG" || fileExtention == ".png"))
                {
                    return(RedirectToAction("ErrorPage"));
                }
                var fileName     = Guid.NewGuid().ToString("N").Substring(0, 10);
                var FileNameFull = fileName + fileExtention;
                var StaticPath   = Path.Combine(uploads, FileNameFull);
                var StaticPathNameNoExtension = Path.Combine(uploads, fileName);
                var RelativePaths             = $"{UserFilesDirectoryRelative}/{fileName}" + $"{fileExtention}";
                //the image will be saved with a unique filename
                FileStream DestinationStream = new FileStream(StaticPath, FileMode.CreateNew);
                imageInput.ImageFile.CopyTo(DestinationStream);
                var DxfFileName       = Guid.NewGuid().ToString("N").Substring(0, 10);
                var DxfFileStaticPath = Path.Combine(uploads, DxfFileName);
                var DxFRelativePaths  = $"{UserFilesDirectoryRelative}/{DxfFileName}" + $"{DxfFileExtension}";
                //Function Here
                //var ExcuationStatus = ModelBuilder(StaticPathNameNoExtension);
                var ExcuationStatus = 0;
                var currentUser     = await _userManager.FindByNameAsync(User.Identity.Name);

                if (ExcuationStatus == 0)
                {
                    var DxfFile = new DxfFile
                    {
                        FileName            = FileNameFull,
                        StaticFilePath      = DxfFileStaticPath + DxfFileExtension,
                        RelativeFilePath    = DxfFileExtension,
                        FK_ApplicatioUserId = currentUser.Id,
                        UploadedTime        = CurrentDate
                    };
                    repo.Add(DxfFile);
                }
                else
                {
                    return(RedirectToAction("ErrorPage"));
                }
                //var ImageFileLocationArray = ImageFileLocationPaths.ToArray();
                return(RedirectToAction("UploadCompelete"));
            }
            else
            {
                return(View("Error"));
            }
        }
コード例 #31
0
        /// <summary>
        /// This creates an image, and any other descriptions
        /// </summary>
        private static Tuple<UIElement, VectorInt> GetPreviewImage(ImageInput image, bool showHash, int imageSize, bool showPerImageDistance, double imageDistPercent)
        {
            const int ALIASMULT = 20;

            #region image

            BitmapSource bitmap;
            if (showHash)
            {
                #region hash

                int width, height;

                bool isColor = false;
                double widthHeight = Math.Sqrt(image.Weights_Orig.Length);
                if (widthHeight.ToInt_Floor() == widthHeight.ToInt_Ceiling())
                {
                    // Black and white, 2D
                    width = height = widthHeight.ToInt_Floor();
                }
                else
                {
                    double widthHeight2 = Math.Sqrt(image.Weights_Orig.Length / 3);
                    if (widthHeight2.ToInt_Floor() == widthHeight2.ToInt_Ceiling())
                    {
                        // Color, 2D
                        isColor = true;
                        width = height = widthHeight2.ToInt_Floor();
                    }
                    else
                    {
                        // Black and white, 1D
                        width = image.Weights_Orig.Length;
                        height = 1;
                    }
                }

                //double? maxValue = image.Weights_Orig.Max() > 1d ? (double?)null : 1d;
                //Convolution2D conv = new Convolution2D(image.Weights_Orig, width, height, false);
                //bitmap = Convolutions.GetBitmap_Aliased(conv, absMaxValue: maxValue, negPosColoring: ConvolutionResultNegPosColoring.BlackWhite, forcePos_WhiteBlack: false);

                if (isColor)
                {
                    bitmap = UtilityWPF.GetBitmap_Aliased_RGB(image.Weights_Orig, width, height, width * ALIASMULT, height * ALIASMULT);
                }
                else
                {
                    bitmap = UtilityWPF.GetBitmap_Aliased(image.Weights_Orig, width, height, width * ALIASMULT, height * ALIASMULT);
                }

                #endregion
            }
            else
            {
                bitmap = UtilityWPF.GetBitmap(image.Image.Filename);
            }

            bitmap = UtilityWPF.ResizeImage(bitmap, imageSize, true);

            Image imageCtrl = new Image()
            {
                Source = bitmap,
            };

            #endregion

            if (!showPerImageDistance)
            {
                // Nothing else needed, just return the image
                return new Tuple<UIElement, VectorInt>(imageCtrl, new VectorInt(bitmap.PixelWidth, bitmap.PixelHeight));
            }

            StackPanel retVal = new StackPanel();

            retVal.Children.Add(imageCtrl);
            retVal.Children.Add(GetPercentVisual(bitmap.PixelWidth, 10, imageDistPercent));

            return new Tuple<UIElement, VectorInt>(retVal, new VectorInt(bitmap.PixelWidth, bitmap.PixelHeight + 10));
        }
コード例 #32
0
        private void DoSimple(ImageInput[] inputs)
        {
            SOMRules rules = GetSOMRules();

            NodeDisplayLayout layout = (NodeDisplayLayout)cboSimpleNodeLayout.SelectedItem;

            bool returnEmptyNodes = layout == NodeDisplayLayout.Disk_All;

            SOMResult result = SelfOrganizingMaps.TrainSOM(inputs, rules, true, returnEmptyNodes);

            SimpleColorScheme scheme = (SimpleColorScheme)cboSimpleOutputColor.SelectedItem;
            var getNodeColor = new Func<SOMNode, Color>(o => GetColor(o.Weights, scheme));

            // Show results
            switch (layout)
            {
                case NodeDisplayLayout.Disk_All:
                    ShowResults_Disk(panelDisplay, result, getNodeColor);
                    break;

                case NodeDisplayLayout.Disk_NonZero:
                    result = SelfOrganizingMaps.ArrangeNodes_LikesAttract(result);
                    ShowResults_Disk(panelDisplay, result, getNodeColor);
                    break;

                case NodeDisplayLayout.Blobs:
                    var events = new SelfOrganizingMapsWPF.BlobEvents(Polygon_MouseMove, Polygon_MouseLeave, null);
                    SelfOrganizingMapsWPF.ShowResults2D_Blobs(panelDisplay, result, getNodeColor, events);

                    // This is for the manual manipulate buttons
                    _nodes = result.Nodes;
                    _imagesByNode = result.InputsByNode;
                    _wasEllipseTransferred = false;
                    break;

                //case NodeDisplayLayout.Grid_UniformSize:
                //    throw new ApplicationException("finish this");
                //    //ShowResults_Grid(panelDisplay, nodes, (SimpleColorScheme)cboSimpleOutputColor.SelectedItem, positions.GridCellSize);
                //    break;

                default:
                    throw new ApplicationException("Unknown SimpleNodeLayout: " + layout.ToString());
            }
        }
コード例 #33
0
        /// <summary>
        /// 处理图片
        /// </summary>
        /// <param name="imageInput"></param>
        /// <returns></returns>
        public async Task <ImageOutput> Processing(ImageInput imageInput, HttpRequest request)
        {
            TempStorageOperation tempStorage = new TempStorageOperation();
            //IStorageService _StorageService = new LocalStorageService();

            //输出结果对象
            ImageOutput imageOutput = new ImageOutput();

            imageOutput.Id       = Guid.NewGuid().ToString();
            imageOutput.Name     = imageInput.Name;
            imageOutput.Tags     = imageInput.Tags;
            imageOutput.Length   = imageInput.File.Length;
            imageOutput.Type     = imageInput.File.ContentType;
            imageOutput.FileName = imageOutput.Id + "." + imageInput.File.ContentType.Split("/")[1];
            imageOutput.Url      = Core.StorageOperation.GetUrl(imageOutput.FileName);
            imageOutput.Path     = Core.StorageOperation.GetPath();

            //写入临时文件夹
            var tempFilePath = await tempStorage.Write(imageInput.File, imageOutput.Id);

            foreach (Core.Interface.IStorageService item in _StorageService)
            {
                await item.CopyDirectory(tempStorage.GetTempPath(imageOutput.Id), Core.StorageOperation.GetSavePath(), true);
            }
            //复制目录


            //保存Json文件
            JsonFile jsonFile = new JsonFile();

            jsonFile.Id         = imageOutput.Id;
            jsonFile.CreateTime = DateTime.Now;
            jsonFile.Name       = imageOutput.Name;
            jsonFile.Tags       = imageOutput.Tags;
            jsonFile.Url        = imageOutput.Url;
            jsonFile.FileName   = imageOutput.FileName;

            //创建处理作业
            var task = new List <JsonFileValues>();

            //预览图
            task.Add(new JsonFileValues()
            {
                Key = "Medium", Status = "0", Value = ""
            });
            //缩略图
            task.Add(new JsonFileValues()
            {
                Key = "Small", Status = "0", Value = ""
            });

            jsonFile.Values = task;
            await jsonFile.SaveAs(tempStorage.GetJsonFilePath(jsonFile.Id));

            //开始处理任务
            await StartJob(jsonFile, tempFilePath);

            //复制目录
            foreach (Core.Interface.IStorageService item in _StorageService)
            {
                await item.CopyDirectory(tempStorage.GetTempPath(jsonFile.Id), Core.StorageOperation.GetSavePath(), true);
            }


            //删除临时目录
            await tempStorage.Delete(jsonFile.Id);

            //返回结果
            return(imageOutput);
        }
コード例 #34
0
        private Canvas DrawVoronoi(VoronoiResult2D voronoi, Color[] colors, SOMNode[] nodes, ImageInput[][] images, int imageWidth, int imageHeight)
        {
            const double MARGINPERCENT = 1.05;

            #region transform

            var aabb = Math2D.GetAABB(voronoi.EdgePoints);
            aabb = Tuple.Create((aabb.Item1.ToVector() * MARGINPERCENT).ToPoint(), (aabb.Item2.ToVector() * MARGINPERCENT).ToPoint());

            TransformGroup transform = new TransformGroup();
            transform.Children.Add(new TranslateTransform(-aabb.Item1.X, -aabb.Item1.Y));
            transform.Children.Add(new ScaleTransform(imageWidth / (aabb.Item2.X - aabb.Item1.X), imageHeight / (aabb.Item2.Y - aabb.Item1.Y)));

            #endregion

            Canvas retVal = new Canvas();

            for (int cntr = 0; cntr < voronoi.ControlPoints.Length; cntr++)
            {
                #region polygon

                Polygon polygon = new Polygon();

                if (voronoi.EdgesByControlPoint[cntr].Length < 3)
                {
                    throw new ApplicationException("Expected at least three edge points");
                }

                Edge2D[] edges = voronoi.EdgesByControlPoint[cntr].Select(o => voronoi.Edges[o]).ToArray();
                Point[] edgePoints = Edge2D.GetPolygon(edges, 1d);

                edgePoints = edgePoints.
                    Select(o => transform.Transform(o)).
                    ToArray();

                foreach (Point point in edgePoints)
                {
                    polygon.Points.Add(point);
                }

                polygon.Fill = new SolidColorBrush(colors[cntr]);
                polygon.Stroke = new SolidColorBrush(UtilityWPF.OppositeColor(colors[cntr], false));
                polygon.StrokeThickness = 1;

                polygon.Tag = Tuple.Create(nodes[cntr], images[cntr]);

                polygon.MouseMove += Polygon_MouseMove_OLD;
                polygon.MouseLeave += Polygon_MouseLeave_OLD;

                retVal.Children.Add(polygon);

                #endregion
            }

            return retVal;
        }
コード例 #35
0
ファイル: SlideController.cs プロジェクト: josdeweger/MVCBlog
        public ActionResult CreateStep3(ImageInput editor)
        {
            var image = new WebImage("~" + editor.Image.ImageUrl);
            var height = image.Height;
            var width = image.Width;
            var tempUrl = editor.Image.ImageUrl;
            var saveUrl = @BlogGlobals.SlideImageFolder + Path.GetFileName(image.FileName);

            image.Crop((int)editor.Top, (int)editor.Left, (int)(height - editor.Bottom), (int)(width - editor.Right));
            image.Resize(190, 190, true, false);
            image.Save(saveUrl);
            System.IO.File.Delete(Server.MapPath(tempUrl));

            ViewBag.PostId = new SelectList(db.Posts, "PostId", "Title");
            ViewBag.imageUrl = saveUrl;

            Slide slide = new Slide();

            return View("CreateStep3", slide);
        }
コード例 #36
0
        private void DoConvolution2(ImageInput[] inputs, double maxSpreadPercent, int minNodeItemsForSplit)
        {
            SOMRules rules = GetSOMRules();

            SOMResult result = SelfOrganizingMaps.TrainSOM(inputs, rules, maxSpreadPercent, true, false);

            var getNodeColor = chkRandomNodeColors.IsChecked.Value ? _getNodeColor_Random : SelfOrganizingMapsWPF.GetNodeColor;

            var events = new SelfOrganizingMapsWPF.BlobEvents(Polygon_MouseMove, Polygon_MouseLeave, null);

            SelfOrganizingMapsWPF.ShowResults2D_Blobs(panelDisplay, result, getNodeColor, events);

            // This is for the manual manipulate buttons
            _nodes = result.Nodes;
            _imagesByNode = result.InputsByNode;
            _wasEllipseTransferred = false;
        }
コード例 #37
0
        private void BuildOverlay2D(SOMNode node, ISOMInput[] images, bool showCount, bool showNodeHash, bool showImageHash, bool showSpread, bool showPerImageDistance)
        {
            const int IMAGESIZE = 80;
            const int NODEHASHSIZE = 100;

            const double SMALLFONT1 = 17;
            const double LARGEFONT1 = 21;
            const double SMALLFONT2 = 15;
            const double LARGEFONT2 = 18;
            const double SMALLFONT3 = 12;
            const double LARGEFONT3 = 14;

            const double SMALLLINE1 = .8;
            const double LARGELINE1 = 1;
            const double SMALLLINE2 = .5;
            const double LARGELINE2 = .85;
            const double SMALLLINE3 = .3;
            const double LARGELINE3 = .7;

            Canvas canvas = new Canvas();
            List<Rect> rectangles = new List<Rect>();

            #region cursor rectangle

            var cursorRect = SelfOrganizingMapsWPF.GetMouseCursorRect(0);
            rectangles.Add(cursorRect.Item1);

            // This is just for debugging
            //Rectangle cursorVisual = new Rectangle()
            //{
            //    Width = cursorRect.Item1.Width,
            //    Height = cursorRect.Item1.Height,
            //    Fill = new SolidColorBrush(UtilityWPF.GetRandomColor(64, 192, 255)),
            //};

            //Canvas.SetLeft(cursorVisual, cursorRect.Item1.Left);
            //Canvas.SetTop(cursorVisual, cursorRect.Item1.Top);

            //canvas.Children.Add(cursorVisual);

            #endregion

            #region count text

            if (showCount)
            {
                StackPanel textPanel = new StackPanel()
                {
                    Orientation = Orientation.Horizontal,
                };

                // "images "
                OutlinedTextBlock text = SelfOrganizingMapsWPF.GetOutlineText("images ", SMALLFONT1, SMALLLINE1);
                text.Margin = new Thickness(0, 0, 4, 0);
                textPanel.Children.Add(text);

                // count
                text = SelfOrganizingMapsWPF.GetOutlineText(images.Length.ToString("N0"), LARGEFONT1, LARGELINE1);
                textPanel.Children.Add(text);

                // Place on canvas
                textPanel.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));       // aparently, the infinity is important to get an accurate desired size
                Size textSize = textPanel.DesiredSize;

                Rect textRect = SelfOrganizingMapsWPF.GetFreeSpot(textSize, new Point(0, 0), new Vector(0, 1), rectangles);
                rectangles.Add(textRect);

                Canvas.SetLeft(textPanel, textRect.Left);
                Canvas.SetTop(textPanel, textRect.Top);

                canvas.Children.Add(textPanel);
            }

            #endregion
            #region spread

            var nodeImages = images.Select(o => o.Weights);
            var allImages = _imagesByNode.SelectMany(o => o).Select(o => o.Weights);

            double nodeSpread = images.Length == 0 ? 0d : SelfOrganizingMaps.GetTotalSpread(nodeImages);
            double totalSpread = SelfOrganizingMaps.GetTotalSpread(allImages);

            if (showSpread && images.Length > 0)
            {
                double nodeStandDev = MathND.GetStandardDeviation(nodeImages);
                double totalStandDev = MathND.GetStandardDeviation(allImages);

                double percentSpread = nodeSpread / totalSpread;
                double pecentStandDev = nodeStandDev / totalSpread;

                Grid spreadPanel = new Grid()
                {
                    Margin = new Thickness(2),
                };
                spreadPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
                spreadPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(4) });
                spreadPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });

                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2) });
                spreadPanel.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });

                AddTextRow(spreadPanel, 0, "node stand dev", (pecentStandDev * 100).ToStringSignificantDigits(2) + "%", SMALLFONT2, LARGEFONT2, SMALLLINE2, LARGELINE2, true);
                AddTextRow(spreadPanel, 2, "node spread", (percentSpread * 100).ToStringSignificantDigits(2) + "%", SMALLFONT2, LARGEFONT2, SMALLLINE2, LARGELINE2, false);

                AddTextRow(spreadPanel, 4, "node stand dev", nodeStandDev.ToStringSignificantDigits(2), SMALLFONT3, LARGEFONT3, SMALLLINE3, LARGELINE3, true);
                AddTextRow(spreadPanel, 6, "node spread", nodeSpread.ToStringSignificantDigits(2), SMALLFONT3, LARGEFONT3, SMALLLINE3, LARGELINE3, false);

                AddTextRow(spreadPanel, 8, "total stand dev", totalStandDev.ToStringSignificantDigits(2), SMALLFONT3, LARGEFONT3, SMALLLINE3, LARGELINE3, true);
                AddTextRow(spreadPanel, 10, "total spread", totalSpread.ToStringSignificantDigits(2), SMALLFONT3, LARGEFONT3, SMALLLINE3, LARGELINE3, false);

                // Place on canvas
                spreadPanel.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));       // aparently, the infinity is important to get an accurate desired size
                Size spreadSize = spreadPanel.DesiredSize;

                Rect spreadRect = SelfOrganizingMapsWPF.GetFreeSpot(spreadSize, new Point(0, 0), new Vector(0, 1), rectangles);
                rectangles.Add(spreadRect);

                Canvas.SetLeft(spreadPanel, spreadRect.Left);
                Canvas.SetTop(spreadPanel, spreadRect.Top);

                canvas.Children.Add(spreadPanel);
            }

            #endregion

            double[] nodeCenter = images.Length == 0 ? node.Weights : MathND.GetCenter(nodeImages);

            #region node hash

            if (showNodeHash)
            {
                ImageInput nodeImage = new ImageInput(null, node.Weights, node.Weights);

                double nodeDist = MathND.GetDistance(nodeImage.Weights, nodeCenter);
                double nodeDistPercent = nodeSpread.IsNearZero() ? 1d : (nodeDist / nodeSpread);     // if zero or one node, then spread will be zero

                Tuple<UIElement, VectorInt> nodeCtrl = GetPreviewImage(nodeImage, true, NODEHASHSIZE, showPerImageDistance, nodeDistPercent);

                // Place on canvas
                Rect nodeRect = SelfOrganizingMapsWPF.GetFreeSpot(new Size(nodeCtrl.Item2.X, nodeCtrl.Item2.Y), new Point(0, 0), new Vector(0, -1), rectangles);
                rectangles.Add(nodeRect);

                Canvas.SetLeft(nodeCtrl.Item1, nodeRect.Left);
                Canvas.SetTop(nodeCtrl.Item1, nodeRect.Top);

                canvas.Children.Add(nodeCtrl.Item1);
            }

            #endregion

            #region images

            foreach (ImageInput image in images)
            {
                double imageDistPercent;
                if (images.Length == 1)
                {
                    imageDistPercent = 1;
                }
                else
                {
                    imageDistPercent = MathND.GetDistance(image.Weights, nodeCenter) / nodeSpread;
                }

                // Create the image (and any other graphics for that image)
                Tuple<UIElement, VectorInt> imageCtrl = GetPreviewImage(image, showImageHash, IMAGESIZE, showPerImageDistance, imageDistPercent);

                // Find a spot for it
                var imageRect = Enumerable.Range(0, 10).
                    Select(o =>
                    {
                        Vector direction = Math3D.GetRandomVector_Circular_Shell(1).ToVector2D();

                        Rect imageRect2 = SelfOrganizingMapsWPF.GetFreeSpot(new Size(imageCtrl.Item2.X, imageCtrl.Item2.Y), new Point(0, 0), direction, rectangles);

                        return new { Rect = imageRect2, Distance = new Vector(imageRect2.CenterX(), imageRect2.CenterY()).LengthSquared };
                    }).
                    OrderBy(o => o.Distance).
                    First().
                    Rect;

                Canvas.SetLeft(imageCtrl.Item1, imageRect.Left);
                Canvas.SetTop(imageCtrl.Item1, imageRect.Top);

                // Add it
                rectangles.Add(imageRect);
                canvas.Children.Add(imageCtrl.Item1);
            }

            #endregion

            Rect canvasAABB = Math2D.GetAABB(rectangles);

            //NOTE: All the items are placed around zero zero, but that may not be half width and height (items may not be centered)
            canvas.RenderTransform = new TranslateTransform(-canvasAABB.Left, -canvasAABB.Top);

            panelOverlay.Children.Clear();
            panelOverlay.Children.Add(canvas);

            _overlayPolyStats = new OverlayPolygonStats(node, images, canvasAABB, cursorRect.Item2, canvas);
        }
コード例 #38
0
        //TODO: Move this section to SelfOrganizingMaps.TrainKMeans()

        private void DoKMeans(ImageInput[] inputs)
        {
            int numNodes = trkKMeansNumNodes.Value.ToInt_Round();

            SOMResult result = SelfOrganizingMaps.TrainKMeans(inputs, numNodes, true);

            var getNodeColor = chkRandomNodeColors.IsChecked.Value ? _getNodeColor_Random : SelfOrganizingMapsWPF.GetNodeColor;

            var events = new SelfOrganizingMapsWPF.BlobEvents(Polygon_MouseMove, Polygon_MouseLeave, Polygon_Click);

            SelfOrganizingMapsWPF.ShowResults2D_Blobs(panelDisplay, result, getNodeColor, events);

            // This is for the manual manipulate buttons
            _nodes = result.Nodes;
            _imagesByNode = result.InputsByNode;
            _wasEllipseTransferred = false;
        }