Example #1
0
        // creates hsl map from given image files - params should be files List<File> - or even better image files
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static java.util.Map<String, FractionHSLData> getFractionHSLDataForDirectory(java.io.File imgDir, org.neuroph.imgrec.image.Dimension samplingResolution) throws java.io.IOException
        public static IDictionary <string, FractionHSLData> getFractionHSLDataForDirectory(File imgDir, Dimension samplingResolution)
        {
            if (!imgDir.Directory)
            {
                throw new System.ArgumentException("The given file must be a directory.  Argument is: " + imgDir);
            }

            IDictionary <string, FractionHSLData> map = new Dictionary <string, FractionHSLData>();
            ImageFilesIterator imagesIterator         = new ImageFilesIterator(imgDir);

            try
            {
                while (imagesIterator.hasNext())
                {
                    File          imgFile = imagesIterator.next();
                    BufferedImage img     = ImageIO.read(imgFile);
                    BufferedImage image   = ImageUtilities.resizeImage(img, samplingResolution.Width, samplingResolution.Height);

                    string filenameOfCurrentImage = imgFile.Name;
                    //String filenameOfCurrentImage = imagesIterator.getFilenameOfCurrentImage();
                    StringTokenizer st = new StringTokenizer(filenameOfCurrentImage, ".");
                    map[st.nextToken()] = new FractionHSLData(image);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            return(map);
        }
Example #2
0
        public static void SavePolygonToImage(Polygon polygon, string fileName, int width, Action <Graphics2D, Affine> render)
        {
            var graphicsAndTransform = ImageWithPolygonOutline(polygon, width);

            render?.Invoke(graphicsAndTransform.graphics, graphicsAndTransform.transform);
            ImageIO.SaveImageData(fileName, graphicsAndTransform.graphics.DestImage);
        }
Example #3
0
        private double PrintTopOfPage(ImageBuffer plateInventoryImage, Graphics2D plateGraphics)
        {
            plateGraphics.Clear(RGBA_Bytes.White);

            double currentlyPrintingHeightPixels = plateInventoryImage.Height - PageMarginMM.Top * PixelPerMM;

            string logoPathAndFile = Path.Combine(ApplicationDataStorage.Instance.ApplicationStaticDataPath, "PartSheetLogo.png");

            if (File.Exists(logoPathAndFile))
            {
                ImageBuffer logoImage = new ImageBuffer();
                ImageIO.LoadImageData(logoPathAndFile, logoImage);
                currentlyPrintingHeightPixels -= logoImage.Height;
                plateGraphics.Render(logoImage, (plateInventoryImage.Width - logoImage.Width) / 2, currentlyPrintingHeightPixels);
            }

            currentlyPrintingHeightPixels -= PartPaddingPixels;

            double          underlineHeightMM = 1;
            RectangleDouble lineBounds        = new RectangleDouble(0, 0, plateInventoryImage.Width - PageMarginPixels.Left * 2, underlineHeightMM * PixelPerMM);

            lineBounds.Offset(PageMarginPixels.Left, currentlyPrintingHeightPixels - lineBounds.Height);
            plateGraphics.FillRectangle(lineBounds, RGBA_Bytes.Black);

            return(currentlyPrintingHeightPixels - (lineBounds.Height + PartPaddingPixels));
        }
Example #4
0
        private static ImageBuffer LoadImageFromDisk(PartThumbnailWidget thumbnailWidget, string stlHashCode, Point2D size)
        {
            ImageBuffer tempImage     = new ImageBuffer(size.x, size.y, 32, new BlenderBGRA());
            string      imageFileName = GetFilenameForSize(stlHashCode, size);

            if (File.Exists(imageFileName))
            {
                if (partExtension == ".png")
                {
                    if (ImageIO.LoadImageData(imageFileName, tempImage))
                    {
                        return(tempImage);
                    }
                }
                else
                {
                    if (ImageTgaIO.LoadImageData(imageFileName, tempImage))
                    {
                        return(tempImage);
                    }
                }
            }

            return(null);
        }
Example #5
0
        public image1Widget()
        {
            AnchorAll();
            string img_name = "spheres.bmp";

            if (!ImageIO.LoadImageData(img_name, sourceImage))
            {
                string buf;
                buf = "File not found: "
                      + img_name
                      + ".bmp"
                      + ". Download http://www.antigrain.com/" + img_name + ".bmp" + "\n"
                      + "or copy it from another directory if available.";
                MessageBox.ShowMessageBox(buf, "Missing Files");
            }
            else
            {
                WindowSize.x = sourceImage.Width + 20;
                WindowSize.y = sourceImage.Height + 40 + 20;
            }

            drawAngle = new MatterHackers.Agg.UI.Slider(new Vector2(5, 5 + 15), new Vector2(295, 7));
            drawScale = new MatterHackers.Agg.UI.Slider(new Vector2(5, 5 + 55), new Vector2(295, 7));
            drawAngle.ValueChanged += new EventHandler(NeedsRedraw);
            drawScale.ValueChanged += new EventHandler(NeedsRedraw);

            AddChild(drawAngle);
            AddChild(drawScale);
            //drawAngle.Text = "Angle={0:F2}";
            //drawScale.Text = "Scale={0:F2}";
            drawAngle.SetRange(-180.0, 180.0);
            drawAngle.Value = 0.0;
            drawScale.SetRange(0.1, 5.0);
            drawScale.Value = 1.0;
        }
Example #6
0
        public void TestMultiSession()
        {
            Tensor imageTensor  = ImageIO.ReadTensorFromImageFile <float>("grace_hopper.jpg", 224, 224, 128.0f, 1.0f);
            int    sessionCount = 10;

            Inception[] graphs           = new Inception[sessionCount];
            bool[]      processCompleted = new bool[sessionCount];
            for (int i = 0; i < sessionCount; i++)
            {
                graphs[i]           = new Inception();
                processCompleted[i] = false;

                graphs[i].OnDownloadCompleted += (sender, e) =>
                {
                    Inception.RecognitionResult[] results = graphs[i].Recognize(imageTensor);

                    processCompleted[i] = true;
                };

                graphs[i].Init();
                Trace.WriteLine(System.String.Format("Reading graph {0}", i));
                Thread.Sleep(1000);
            }

            while (!processCompleted.All((v) => v))
            {
                Thread.Sleep(1000);
            }
        }
Example #7
0
        static void Main()
        {
            //load from the Web
            var image = new Uri("http://vignette3.wikia.nocookie.net/disney/images/5/5d/Lena_headey_.jpg")
                        .GetBytes()
                        .DecodeAsColorImage();

            //show image
            image.Show("New Lena"); //to zoom or translate: press and hold Shift and scroll or move your mouse

            image = new Bgr <byte> [480, 640];

            //draw something
            image.Draw(new Rectangle(50, 50, 200, 100), Bgr <byte> .Red, -1);
            image.Draw(new Circle(50, 50, 25), Bgr <byte> .Blue, 5);
            image.Draw(new Box2D(new Point(250, 150), new Size(100, 100), 30), Bgr <byte> .Green, 1);
            image.Draw("Hello world!", Font.Big, new Point(10, 100), Bgr <byte> .White);

            //save and load
            image.Save("out.png");
            ImageIO.LoadColor("out.png").Clone().Show("Saved image", scaleForm: true);

            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();
            UI.CloseAll();
        }
Example #8
0
        unsafe static void Main()
        {
            var resourceDir = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, "Resources");
            var imgColor    = ImageIO.LoadColor(Path.Combine(resourceDir, "testColorBig.jpg")).Clone();

            var rImg = imgColor.AsEnumerable().Select(x => x.G).ToArray2D(imgColor.Width(), imgColor.Height());
        }
Example #9
0
        public void TestMultiboxPeopleDetect()
        {
            Tensor imageResults = ImageIO.ReadTensorFromImageFile <float>("surfers.jpg", 224, 224, 128.0f, 1.0f / 128.0f);

            MultiboxGraph multiboxGraph    = new MultiboxGraph();
            bool          processCompleted = false;

            multiboxGraph.OnDownloadCompleted += (sender, e) =>
            {
                MultiboxGraph.Result[] result = multiboxGraph.Detect(imageResults);

                //Bitmap bmp = new Bitmap("surfers.jpg");
                //MultiboxGraph.DrawResults(bmp, result, 0.1f);
                //MultiboxGraph.
                //bmp.Save("surfers_result.jpg");
                processCompleted = true;
            };

            multiboxGraph.Init();

            while (!processCompleted)
            {
                Thread.Sleep(1000);
            }
        }
Example #10
0
        static void Main()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";runtimes/win10-x64/"); //only needed if projects are directly referenced

            //load from the Web
            var image = new Uri("http://vignette3.wikia.nocookie.net/disney/images/5/5d/Lena_headey_.jpg")
                        .GetBytes()
                        .DecodeAsColorImage();

            //show image
            image.Show("New Lena"); //to zoom or translate: press and hold Shift and scroll or move your mouse

            //draw something
            image.Draw(new Rectangle(50, 50, 200, 100), Bgr <byte> .Red, -1);
            image.Draw(new Circle(50, 50, 25), Bgr <byte> .Blue, 5);
            image.Draw(new Box2D(new Point(250, 150), new Size(100, 100), 30), Bgr <byte> .Green, 1);
            image.Draw("Hello world!", Font.Big, new Point(10, 100), Bgr <byte> .White);

            //save and load
            image.Save("out.png");
            ImageIO.LoadColor("out.png").Clone().Show("Saved image", scaleForm: true);

            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();
            UI.CloseAll();
        }
Example #11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public void writeEnd() throws java.io.IOException
            public override void writeEnd()
            {
                if (!ImageIO.write(im, fileFormat, new File(fileName)))
                {
                    Console.WriteLine(string.Format("Cannot save image in format {0} using ImageIO: {1}", fileFormat, fileName));
                }
            }
Example #12
0
        public static void Paste(this ISceneContext sceneContext)
        {
            var scene = sceneContext.Scene;

            if (Clipboard.Instance.ContainsImage)
            {
                // Persist
                string filePath = ApplicationDataStorage.Instance.GetNewLibraryFilePath(".png");
                ImageIO.SaveImageData(
                    filePath,
                    Clipboard.Instance.GetImage());

                scene.UndoBuffer.AddAndDo(
                    new InsertCommand(
                        scene,
                        new ImageObject3D()
                {
                    AssetPath = filePath
                }));
            }
            else if (Clipboard.Instance.ContainsText)
            {
                if (Clipboard.Instance.GetText() == "!--IObjectSelection--!")
                {
                    sceneContext.DuplicateItem(0, ApplicationController.ClipboardItem);
                    // each time we put in the object offset it a bit more
                    pasteObjectXOffset += 5;
                }
            }
        }
Example #13
0
        public static string Predict(string ModelFile = " ", string LabelFile = " ", string inputFile = " ")
        {
            ModelDeploy modelDecoderGraph = new ModelDeploy(  );

            modelDecoderGraph.Init(new string[] { ModelFile, LabelFile }, "Mul", "final_result");

            Tensor imageTensor = ImageIO.ReadTensorFromImageFile(inputFile, 299, 299, 128.0f, 1.0f / 128.0f);
            //modelDecoderGraph.ImportGraph();
            Stopwatch sw = Stopwatch.StartNew();

            float[] probability = modelDecoderGraph.Recognize(imageTensor);
            sw.Stop();

            String resStr = String.Empty;

            if (probability != null)
            {
                String[] labels = modelDecoderGraph.Labels;
                float    maxVal = 0;
                int      maxIdx = 0;
                for (int i = 0; i < probability.Length; i++)
                {
                    if (probability[i] > maxVal)
                    {
                        maxVal = probability[i];
                        maxIdx = i;
                    }
                }
                resStr = String.Format("Object is {0} with {1}% probability. \n Recognition done in {2} milliseconds.", labels[maxIdx], maxVal * 100, sw.ElapsedMilliseconds);
            }

            return(resStr);
        }
Example #14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static void main(String[] args) throws java.io.IOException
        public static void Main(string[] args)
        {
            // User input parameters
            //*******************************************************************************************************************************************
            string imagePath   = "C:/Users/Mihailo/Desktop/OCR/tekst.png";    //path to the image with letters (document) for recognition
            string textPath    = "C:/Users/Mihailo/Desktop/OCR/tekst.txt";    // path to the .txt file where the recognized text will be stored
            string networkPath = "C:/Users/Mihailo/Desktop/OCR/network.nnet"; // locatoin of the trained network
            int    fontSize    = 12;                                          // fontSize, predicted by height of the letters, minimum font size is 12 pt
            int    scanQuality = 300;                                         // scan quality, minimum quality is 300 dpi
            //*******************************************************************************************************************************************

            BufferedImage    image = ImageIO.read(new File(imagePath));
            ImageFilterChain chain = new ImageFilterChain();

            chain.addFilter(new GrayscaleFilter());
            chain.addFilter(new OtsuBinarizeFilter());
            BufferedImage binarizedImage = chain.processImage(image);

            // Information about letters and text
            Letter letterInfo = new Letter(scanQuality, binarizedImage);
            //        letterInfo.recognizeDots(); // call this method only if you want to recognize dots and other litle characters, TODO
            Text textInfo = new Text(binarizedImage, letterInfo);

            OCRTextRecognition recognition = new OCRTextRecognition(letterInfo, textInfo);

            recognition.NetworkPath = networkPath;

            recognition.recognize();

            //if you want to save recognized text
            //        recognition.setRecognizedTextPath(textPath);
            //        recognition.saveText();

            Console.WriteLine(recognition.RecognizedText);
        }
Example #15
0
        private static void DownloadImageAsync(ImageSequence imageSequenceToLoadInto, string uriToLoad, Action doneLoading, ImageSequence asyncImageSequence, string pngFileName, string gifFileName)
        {
            WebClient client = new WebClient();

            client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) =>
            {
                try                 // if we get a bad result we can get a target invocation exception. In that case just don't show anything
                {
                    Task.Run(() =>
                    {
                        // scale the loaded image to the size of the target image
                        byte[] raw    = e.Result;
                        Stream stream = new MemoryStream(raw);

                        lock (locker)
                        {
                            StaticData.Instance.LoadImageSequenceData(stream, asyncImageSequence);
                        }

                        if (asyncImageSequence.Frames.Count == 1)
                        {
                            // save the as png
                            lock (locker)
                            {
                                if (!File.Exists(pngFileName))
                                {
                                    ImageIO.SaveImageData(pngFileName, asyncImageSequence.Frames[0]);
                                }
                            }
                        }
                        else                         // save original stream as gif
                        {
                            using (var writter = new FileStream(gifFileName, FileMode.Create))
                            {
                                stream.Position = 0;
                                stream.CopyTo(writter);
                            }
                        }

                        UiThread.RunOnIdle(() =>
                        {
                            imageSequenceToLoadInto.Copy(asyncImageSequence);
                            imageSequenceToLoadInto.Invalidate();
                            doneLoading?.Invoke();
                        });
                    });
                }
                catch
                {
                }
            };

            try
            {
                client.DownloadDataAsync(new Uri(uriToLoad));
            }
            catch
            {
            }
        }
Example #16
0
        public static ImageBuffer LoadImageFromDisk(string stlHashCode)
        {
            try
            {
                ImageBuffer tempImage     = new ImageBuffer(BigRenderSize.x, BigRenderSize.y);
                string      imageFileName = GetImageFileName(stlHashCode);

                if (File.Exists(imageFileName))
                {
                    if (partExtension == ".png")
                    {
                        if (ImageIO.LoadImageData(imageFileName, tempImage))
                        {
                            return(tempImage);
                        }
                    }
                    else
                    {
                        if (ImageTgaIO.LoadImageData(tempImage, imageFileName))
                        {
                            return(tempImage);
                        }
                    }
                }
            }
            catch
            {
            }

            return(null);
        }
Example #17
0
        public void TestEncodeJpeg()
        {
            Tensor image = ImageIO.ReadTensorFromImageFile("surfers.jpg");

            byte[] jpegRaw = ImageIO.EncodeJpeg(image);
            File.WriteAllBytes("surefers_out.jpg", jpegRaw);
        }
Example #18
0
    private void RecognizeAndUpdateText(Texture2D texture)
    {
        if (_inceptionGraph == null)
        {
            return;
        }
        Tensor imageTensor = ImageIO.ReadTensorFromTexture2D(texture, 224, 224, 128.0f, 1.0f, true);

        float[] probability = _inceptionGraph.Recognize(imageTensor);

        //String resStr = String.Empty;
        if (probability != null)
        {
            float maxVal = 0;
            int   maxIdx = 0;
            for (int i = 0; i < probability.Length; i++)
            {
                if (probability[i] > maxVal)
                {
                    maxVal = probability[i];
                    maxIdx = i;
                }
            }
            DisplayText.text = String.Format("Object is {0} with {1}% probability.", _inceptionLabels[maxIdx], maxVal * 100);
        }
    }
Example #19
0
        unsafe static void Main()
        {
            var resourceDir = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, "Resources");
            var imgColor    = ImageIO.LoadColor(Path.Combine(resourceDir, "testColorBig.jpg")).Clone();

            //imgColor = imgColor.CorrectContrast(105);
        }
        private static ImageBuffer LoadImageFromDisk(PartThumbnailWidget thumbnailWidget, string stlHashCode)
        {
            ImageBuffer tempImage     = new ImageBuffer(BigRenderSize.x, BigRenderSize.y);
            string      imageFileName = GetImageFileName(stlHashCode);

            if (File.Exists(imageFileName))
            {
                if (partExtension == ".png")
                {
                    if (ImageIO.LoadImageData(imageFileName, tempImage))
                    {
                        return(tempImage);
                    }
                }
                else
                {
                    if (ImageTgaIO.LoadImageData(imageFileName, tempImage))
                    {
                        return(tempImage);
                    }
                }
            }

            return(null);
        }
Example #21
0
        List <TemplatePyramid> fromFiles()
        {
            Console.WriteLine("Building templates from files...");

            var list = new List <TemplatePyramid>();

            string resourceDir = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, "Resources", "OpenHandLeft_BW");

            string[] files = Directory.GetFiles(resourceDir, "*.bmp");

            object syncObj = new object();

            Parallel.ForEach(files, delegate(string file)
                             //foreach(var file in files)
            {
                Gray <byte>[,] preparedBWImage = ImageIO.LoadGray(file).Clone();

                try
                {
                    var tp = TemplatePyramid.CreatePyramidFromPreparedBWImage(preparedBWImage, new FileInfo(file).Name /*"OpenHand"*/);
                    lock (syncObj)
                    { list.Add(tp); };
                }
                catch (Exception)
                {}
            });

            //XMLTemplateSerializer<ImageTemplatePyramid, ImageTemplate>.Save(list, "C:/bla.xml");
            return(list);
        }
        public ImageLinkAdvancedX(string url)
        {
            HAnchor  = HAnchor.Fit;
            VAnchor  = VAnchor.Fit;
            this.Url = url;

            var imageBuffer = new ImageBuffer(icon);
            var imageWidget = new ImageWidget(imageBuffer);

            this.AddChild(imageWidget);

            try
            {
                if (url.StartsWith("http"))
                {
                    client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ContinueWith(task =>
                    {
                        var response = task.Result;

                        if (response.IsSuccessStatusCode)
                        {
                            response.Content.ReadAsStreamAsync().ContinueWith(streamTask =>
                            {
                                // response.Headers.TryGetValues("", s[""] == "" ||
                                if (string.Equals(Path.GetExtension(url), ".svg", StringComparison.OrdinalIgnoreCase))
                                {
                                    // Load svg into SvgWidget, swap for ImageWidget
                                    try
                                    {
                                        var svgWidget = new SvgWidget(streamTask.Result, 1)
                                        {
                                            Border      = 1,
                                            BorderColor = Color.YellowGreen
                                        };

                                        this.ReplaceChild(imageWidget, svgWidget);
                                    }
                                    catch (Exception svgEx)
                                    {
                                        Debug.WriteLine("Error loading svg: {0} :: {1}", url, svgEx.Message);
                                    }
                                }
                                else
                                {
                                    // Load img
                                    if (!ImageIO.LoadImageData(streamTask.Result, imageBuffer))
                                    {
                                        Debug.WriteLine("Error loading image: " + url);
                                    }
                                }
                            });
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #23
0
        public void TestEncodeJpeg()
        {
            Tensor image = ImageIO.ReadTensorFromImageFile <float>("surfers.jpg", 299, 299, 0, 1.0f / 255.0f, true, false);

            byte[] jpegRaw = ImageIO.TensorToJpeg(image, 255.0f, 0.0f);
            File.WriteAllBytes("surefers_out.jpg", jpegRaw);
        }
Example #24
0
 private void ProcessResources(PDResources resources, string prefix, bool addKey)
 {
     if (resources != null)
     {
         Iterator iterator = resources.getXObjectNames().iterator();
         int      num      = 1;
         while (iterator.hasNext())
         {
             COSName cOSName = (COSName)iterator.next();
             string  str     = null;
             str = (!addKey ? this.GetUniqueFileName(prefix, ".jpg") : this.GetUniqueFileName(string.Concat(prefix, "_", num), ".jpg"));
             PDResources.OutputFileName = string.Concat(str, ".jpg");
             PDXObject xObject = resources.getXObject(cOSName);
             if (resources.isImageXObject(cOSName))
             {
                 PDImageXObject pDImageXObject = (PDImageXObject)xObject;
                 str = (!addKey ? this.GetUniqueFileName(prefix, pDImageXObject.getSuffix()) : this.GetUniqueFileName(string.Concat(prefix, "_", num), pDImageXObject.getSuffix()));
                 Console.WriteLine(string.Concat("Writing image:", str));
                 try
                 {
                     BufferedImage image = pDImageXObject.getImage();
                     ImageIO.write(image, "jpg", new java.io.File(string.Concat(str, ".jpg")));
                 }
                 catch (Exception exception)
                 {
                     Console.WriteLine("Could not write image: {0}.{1}{2}", str, Environment.NewLine, exception.Message);
                 }
             }
             else if (xObject is PDFormXObject)
             {
                 this.ProcessResources(((PDFormXObject)xObject).getResources(), prefix, addKey);
             }
         }
     }
 }
Example #25
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static java.awt.image.BufferedImage imageFromBytes(int paramInt, byte[] paramArrayOfByte) throws Exception
        public static BufferedImage imageFromBytes(int paramInt, sbyte[] paramArrayOfByte)
        {
            string str = "jpg";

            if (paramInt == 1)
            {
                str = "png";
            }
            else if (paramInt == 3)
            {
                str = "gif";
            }
            MemoryStream byteArrayInputStream1 = new MemoryStream(paramArrayOfByte);

            System.Collections.IEnumerator iterator = ImageIO.getImageReadersByFormatName(str);
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ImageReader      imageReader           = (ImageReader)iterator.next();
            MemoryStream     byteArrayInputStream2 = byteArrayInputStream1;
            ImageInputStream imageInputStream      = ImageIO.createImageInputStream(byteArrayInputStream2);

            imageReader.setInput(imageInputStream, true);
            ImageReadParam imageReadParam = imageReader.DefaultReadParam;
            BufferedImage  bufferedImage  = imageReader.read(0, imageReadParam);

            return(createBufferedImage(bufferedImage, paramInt, bufferedImage.getWidth(null), bufferedImage.getHeight(null)));
        }
        private void OnDownloadComplete(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                var stringResult = new StringBuilder();

                using (var imageTensor = ImageIO.ReadTensorFromImageFile <float>(_fileName, 256, 256))
                {
                    var results = _inceptionGraph.Recognize(imageTensor);

                    foreach (var recognitionResult in results.OrderByDescending(x => x.Probability).Take(5))
                    {
                        if (decimal.TryParse(recognitionResult.Probability.ToString(), out decimal resultResult))
                        {
                            stringResult.Append($"Object is {recognitionResult.Label} with {resultResult}% probability.")
                            .AppendLine();
                        }
                    }
                }

                InformationText = stringResult.ToString();
                IsModalVisible  = false;
            }
            catch (Exception ex)
            {
                _exceptionLogDataAccess.LogException(ex.ToString());
            }
            IsModalVisible = false;
        }
        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            byte[]      raw           = e.Result;
            Stream      stream        = new MemoryStream(raw);
            ImageBuffer unScaledImage = new ImageBuffer(10, 10, 32, new BlenderBGRA());

            ImageIO.LoadImageData(stream, unScaledImage);
            // If the source image (the one we downloaded) is more than twice as big as our dest image.
            while (unScaledImage.Width > Image.Width * 2)
            {
                // The image sampler we use is a 2x2 filter so we need to scale by a max of 1/2 if we want to get good results.
                // So we scale as many times as we need to to get the Image to be the right size.
                // If this were going to be a non-uniform scale we could do the x and y separatly to get better results.
                ImageBuffer halfImage = new ImageBuffer(unScaledImage.Width / 2, unScaledImage.Height / 2, 32, scalingBlender);
                halfImage.NewGraphics2D().Render(unScaledImage, 0, 0, 0, halfImage.Width / (double)unScaledImage.Width, halfImage.Height / (double)unScaledImage.Height);
                unScaledImage = halfImage;
            }
            Image.NewGraphics2D().Render(unScaledImage, 0, 0, 0, Image.Width / (double)unScaledImage.Width, Image.Height / (double)unScaledImage.Height);
            Image.MarkImageChanged();
            Invalidate();

            if (LoadComplete != null)
            {
                LoadComplete(this, null);
            }
        }
        private bool parseImage()

        {
            _image = ImageIO.read(_is);

            _width  = _image.getWidth();
            _height = _image.getHeight();

            TempStream  ts = new TempStream();
            WriteStream os = new WriteStream(ts);

            try {
                ImageIO.write(_image, "jpeg", os);
            } finally {
                os.close();
            }

            /*
             * os = Vfs.openWrite("file:/tmp/caucho/qa/test.jpg");
             * try {
             * ImageIO.write(_image, "jpeg", os);
             * } finally {
             * os.close();
             * }
             *
             * os = Vfs.openWrite("file:/tmp/caucho/qa/test.png");
             * try {
             * ImageIO.write(_image, "png", os);
             * } finally {
             * os.close();
             * }
             */

            return(parseImageJpeg(ts.openRead()));
        }
Example #29
0
        private void LoadTexture(string path, Stream stream, bool rawimg)
        {
            try {
                var texTask = rawimg
                                        ? ImageIO.RawToTexture2DAsync(Main.instance.GraphicsDevice, new BinaryReader(stream))
                                        : ImageIO.PngToTexture2DAsync(Main.instance.GraphicsDevice, stream);

                AsyncLoadQueue.Enqueue(texTask.ContinueWith(t => {
                    if (t.Exception != null)
                    {
                        throw new ResourceLoadException(
                            Language.GetTextValue("tModLoader.LoadErrorTextureFailedToLoad", path), t.Exception);
                    }

                    var tex  = t.Result;
                    tex.Name = Name + "/" + path;
                    lock (textures)
                        textures[path] = tex;
                }));
            }
            catch (Exception e) {
                throw new ResourceLoadException(Language.GetTextValue("tModLoader.LoadErrorTextureFailedToLoad", path), e);
            }
            finally {
                stream.Close();
            }
        }
Example #30
0
        private void loadImageOfUser(string paramString)
        {
            string str = DatabaseDBUtil.Properties.ConnectionHost;

            if (this.imgcIcon == null && !string.ReferenceEquals(str, null))
            {
                if (DatabaseDBUtil.Enterprise)
                {
                    if (!str.StartsWith("http://", StringComparison.Ordinal) && !str.StartsWith("https://", StringComparison.Ordinal))
                    {
                        str = "http://" + str;
                    }
                    string str1 = str + "/ces/pictures/showAvatar?userId=" + DatabaseDBUtil.Properties.UserId;
                    try
                    {
                        BufferedImage bufferedImage1 = ImageIO.read((new URL(str1)).openStream());
                        BufferedImage bufferedImage2 = ImageUtils.resizeImage(bufferedImage1, 1, 12, 12);
                        this.imgcIcon = new ImageIcon(bufferedImage2);
                    }
                    catch (Exception)
                    {
                        this.imgcIcon = new ImageIcon();
                    }
                }
                else
                {
                    this.imgcIcon = new ImageIcon();
                }
            }
            if (this.imgcIcon != null)
            {
                ((JideButton)this.o_trailingButton).Icon = this.imgcIcon;
            }
        }
Example #31
0
 public string Info(string fileName)
 {
     string s = "";
     ImageIO io1 = new ImageIO();
     int page = 1;
     ImageInfo oInfo;
     oInfo = io1.Info (fileName, page);
     int pages = oInfo.PageCount;
     txtRslt.Text = txtRslt.Text +  ShowInfo(oInfo, page);
     for (page = 2; page <= Math.Min(pages, 20); page++)
         {
         oInfo = io1.Info (fileName, page);
         txtRslt.Text = txtRslt.Text + ShowInfo(oInfo, page);
         System.Windows.Forms.Application.DoEvents();
         }
         return txtRslt.Text;
 }
Example #32
0
 private void DisplayImage(string fileName)
 {
     try
     {
         PictureBox1.Image = null;
         if (!System.IO.File.Exists(fileName)) return;
         ImageIO io = new ImageIO();
         Bitmap newImage = io.Open(fileName);
         double scaleX = (double) PictureBox1.Width / (double) newImage.Width;
         double scaleY = (double) PictureBox1.Height / (double) newImage.Height;
         double Scale = Math.Min(scaleX, scaleY);
         int w = (int) (newImage.Width * Scale);
         int h = (int) (newImage.Height * Scale);
         PictureBox1.Image = newImage.GetThumbnailImage(w, h, new System.Drawing.Image.GetThumbnailImageAbort(GetThumbnailImageAbort), IntPtr.Zero);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Image is not displayed because:" + Environment.NewLine + ex.Message);
     }
 }
Example #33
0
 public string Read1DPro_Page_Zones(string fileName, int page)
 {
     string s = "";
         BarcodeReader reader = new BarcodeReader();
         // for faster reading specify only required direction
         reader.Horizontal = true; reader.Vertical = true; reader.Diagonal = true;
     #if false
         // For faster processing specify expected types
         reader.Code128 = true;
         reader.Code39 = true;
     #else
         // Read all most popular barcode types
         reader.Auto1D = true;
     #endif
         ImageIO io = new ImageIO();
         ImageInfo info = io.Info(fileName, page);
         s = s + "======= Barcode in ZONE (upper half of the image) ===========" + Environment.NewLine;
         // Set zone to top half of the image
         reader.Zone = new Rectangle (0,0,info.Width, info.Height/2);
         Barcode[] barcodes = reader.Read (fileName, page);
         int cnt = 0;
         foreach (Barcode bc in barcodes)
             {cnt++; AddBarcode(ref s, cnt, bc); }
         if (cnt == 0) 		{ s = s + "NO BARCODES"; 	}
         s = s +  Environment.NewLine;
         s = s + "======= Barcode in IMAGE ===========" + Environment.NewLine;
         // Disable zone
         reader.Zone = new Rectangle ();
         barcodes = reader.Read (fileName, page);
         cnt = 0;
         foreach (Barcode bc in barcodes)
             {cnt++; AddBarcode(ref s, cnt, bc); }
         if (cnt == 0) 		{ s = s + "NO BARCODES"; 	}
         return  s;
 }