예제 #1
1
파일: Form1.cs 프로젝트: pkt-fit-knu/I21-07
        private void button_Click(object sender, EventArgs e)
        {
            Stream stream = null;

            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((stream = openFileDialog.OpenFile()) != null)
                    {
                        using (stream)
                        {
                            string pathName = openFileDialog.FileName;

                            Bitmap image = new Bitmap(pathName);

                            pictureBox1.Image = image.Resize(pictureBox1.Width, pictureBox1.Height);

                            Mask mask = new Mask(new int[,] { { 1, 1, 1 }, { 1, -8, 1 }, { 1, 1, 1 } });

                            image = LaplacianSharper.SharpImage(image, mask);

                            pictureBox2.Image = image.Resize(pictureBox2.Width, pictureBox2.Height);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
예제 #2
0
파일: Form1.cs 프로젝트: pkt-fit-knu/I21-07
        private void button_Click(object sender, EventArgs e)
        {
            Stream stream = null;

            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((stream = openFileDialog.OpenFile()) != null)
                    {
                        using (stream)
                        {
                            string pathName = openFileDialog.FileName;

                            Bitmap image = new Bitmap(pathName);

                            pictureBox1.Image = image.Resize(pictureBox1.Width, pictureBox1.Height);

                            Histogram histogram1 = new Histogram();

                            histogram1.SetIntensities(image);

                            histogram1.DrawHistogram(chart1);

                            chart1.Visible = true;

                            this.Controls.Add(chart1);

                            Histogram histogram2 = new Histogram();

                            image = histogram1.BalanceImage(image);

                            pictureBox2.Image = image.Resize(pictureBox2.Width, pictureBox2.Height);

                            histogram2.SetIntensities(image);

                            histogram2.DrawHistogram(chart2);

                            chart2.Visible = true;

                            this.Controls.Add(chart2);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
예제 #3
0
        public void ResizeDown()
        {
            Image image = new Bitmap(500, 500);

            var newImage = image.Resize(100, 200);

            Assert.AreEqual(newImage.Width, 100);
            Assert.AreEqual(newImage.Height, 200);
        }
예제 #4
0
        public void ChooseImage(int id)
        {
            var filePaths = Directory.GetFiles(string.Format(@"C:\Users\Dimitar\Pictures\FilterIT\{0}\", User.Identity.Name), "*.png");
            var img = new Bitmap(filePaths[id]);

            int height = (int)(img.Height / ((float)img.Width / 500f));
            var filteredImages = img.Resize(500, height).ApplyFilters();

            Session["Image"] = img;
            Session["ImageName"] = Path.GetFileName(filePaths[id]);
            Session["FilteredImages"] = filteredImages;
        }
 public static bool Resize(this string sourcePath, string destinationPath, Size size)
 {
     if (File.Exists(sourcePath))
     {
         using (Image image = new Bitmap(sourcePath))
         {
             using (Image resized = image.Resize(size))
             {
                 resized.Save(destinationPath, ImageFormat.Jpeg);
             }
         }
         return true;
     }
     return false;
 }
예제 #6
0
        public string GetThumbnails(HttpPostedFileBase fileUpload)
        {
            var stream = fileUpload.InputStream;
            Bitmap img = new Bitmap(stream);

            if(User.Identity.IsAuthenticated)
                SaveImage(fileUpload.FileName, img);

            int height = (int)(img.Height / ((float)img.Width / 500f));
            var filteredImages = img.Resize(500, height).ApplyFilters();

            Session["Image"] = img;
            Session["ImageName"] = fileUpload.FileName;
            Session["FilteredImages"] = filteredImages;

            return filteredImages;
        }
        private static Bitmap CreateLastPositionImage(Bitmap source)
        {
            try
            {
                var img = new Bitmap(source.Width, source.Width);
                var cropRect = new Rectangle(0, 0, source.Width, source.Width);

                using (var sourceImage = source)
                {
                    using (var croppedImage = sourceImage.Clone(cropRect, sourceImage.PixelFormat))
                    {
                        using (var tb = new TextureBrush(croppedImage))
                        {
                            using (var g = Graphics.FromImage(img))
                            {
                                g.FillEllipse(tb, 0, 0, source.Width, source.Width);
                                g.DrawEllipse(
                                    new Pen(Color.FromArgb(86, 86, 86), 6) { Alignment = PenAlignment.Inset }, 0, 0,
                                    source.Width, source.Width);
                            }
                        }
                    }
                }
                return img.Resize(24, 24).Grayscale();
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
            return null;
        }
예제 #8
0
파일: Program.cs 프로젝트: Microsoft/CNTK
        /// <summary>
        /// This method shows how to evaluate a trained image classification model, with
        /// explicitly created feature vectors.
        /// </summary>
        public static List<float> EvaluateImageInputUsingFeatureVector()
        {
            List<float> outputs = null;

            try
            {
                // This example requires the RestNet_18 model.
                // The model can be downloaded from <see cref="https://www.cntk.ai/resnet/ResNet_18.model"/>
                // The model is assumed to be located at: <CNTK>\Examples\Image\Classification\ResNet
                // along with a sample image file named "zebra.jpg".
                Environment.CurrentDirectory = initialDirectory;

                using (var model = new IEvaluateModelManagedF())
                {
                    model.CreateNetwork(string.Format("modelPath=\"{0}\"", resnetModelFilePath), deviceId: -1);

                    // Prepare input value in the appropriate structure and size
                    var inDims = model.GetNodeDimensions(NodeGroup.Input);
                    if (inDims.First().Value != resNetImageSize * resNetImageSize * 3)
                    {
                        throw new CNTKRuntimeException(string.Format("The input dimension for {0} is {1} which is not the expected size of {2}.", inDims.First(), inDims.First().Value, 224 * 224 * 3), string.Empty);
                    }

                    // Transform the image
                    Bitmap bmp = new Bitmap(Bitmap.FromFile(imageFileName));
                    var resized = bmp.Resize(resNetImageSize, resNetImageSize, true);

                    var resizedCHW = resized.ParallelExtractCHW();
                    var inputs = new Dictionary<string, List<float>>() { {inDims.First().Key, resizedCHW } };

                    // We can call the evaluate method and get back the results (single layer output)...
                    var outDims = model.GetNodeDimensions(NodeGroup.Output);
                    outputs = model.Evaluate(inputs, outDims.First().Key);
                }

                // Retrieve the outcome index (so we can compare it with the expected index)
                var max = outputs.Select((value, index) => new { Value = value, Index = index })
                    .Aggregate((a, b) => (a.Value > b.Value) ? a : b)
                    .Index;

                Console.WriteLine("EvaluateImageInputUsingFeatureVector: Outcome = {0}", max);
            }
            catch (CNTKException ex)
            {
                OnCNTKException(ex);
            }
            catch (Exception ex)
            {
                OnGeneralException(ex);
            }
            return outputs;
        }
 public void Resize()
 {
     using (Bitmap TestObject = new Bitmap(@"..\..\Data\Image\Lenna.jpg"))
     {
         using (Bitmap Image = Assert.Do<Bitmap>(() => TestObject.Resize(50, Utilities.Media.Image.ExtensionMethods.BitmapExtensions.Quality.Low, @".\Testing\LennaResize.jpg")))
         {
             Assert.NotNull(Image);
             Assert.Equal(50,Image.Width);
             Assert.Equal(50, Image.Height);
         }
     }
 }
예제 #10
0
        /// <summary>
        /// This method shows how to evaluate a trained image classification model
        /// </summary>
        public static void EvaluateImageClassificationModel()
        {
            try
            {
                // This example requires the RestNet_18 model.
                // The model can be downloaded from <see cref="https://www.cntk.ai/resnet/ResNet_18.model"/>
                // The model is assumed to be located at: <CNTK>\Examples\Image\Miscellaneous\ImageNet\ResNet 
                // along with a sample image file named "zebra.jpg".
                string workingDirectory = Path.Combine(initialDirectory, @"..\..\Examples\Image\Miscellaneous\ImageNet\ResNet");
                Environment.CurrentDirectory = initialDirectory;

                List<float> outputs;

                using (var model = new IEvaluateModelManagedF())
                {
                    string modelFilePath = Path.Combine(workingDirectory, "ResNet_18.model");
                    model.CreateNetwork(string.Format("modelPath=\"{0}\"", modelFilePath), deviceId: -1);

                    // Prepare input value in the appropriate structure and size
                    var inDims = model.GetNodeDimensions(NodeGroup.Input);
                    if (inDims.First().Value != 224 * 224 * 3)
                    {
                        throw new CNTKRuntimeException(string.Format("The input dimension for {0} is {1} which is not the expected size of {2}.", inDims.First(), inDims.First().Value, 224 * 224 * 3), string.Empty);
                    }

                    // Transform the image
                    string imageFileName = Path.Combine(workingDirectory, "zebra.jpg");
                    Bitmap bmp = new Bitmap(Bitmap.FromFile(imageFileName));

                    var resized = bmp.Resize(224, 224, true);
                    var resizedCHW = resized.ParallelExtractCHW();
                    var inputs = new Dictionary<string, List<float>>() { {inDims.First().Key, resizedCHW } };

                    // We can call the evaluate method and get back the results (single layer output)...
                    var outDims = model.GetNodeDimensions(NodeGroup.Output);
                    outputs = model.Evaluate(inputs, outDims.First().Key);
                }

                // Retrieve the outcome index (so we can compare it with the expected index)
                var max = outputs.Select((value, index) => new { Value = value, Index = index })
                    .Aggregate((a, b) => (a.Value > b.Value) ? a : b)
                    .Index;

                Console.WriteLine("Outcome: {0}", max);
            }
            catch (CNTKException ex)
            {
                Console.WriteLine("Error: {0}\nNative CallStack: {1}\n Inner Exception: {2}", ex.Message, ex.NativeCallStack, ex.InnerException != null ? ex.InnerException.Message : "No Inner Exception");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}\nCallStack: {1}\n Inner Exception: {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : "No Inner Exception");
            }
        }
예제 #11
0
 /// <summary>
 /// Makes a scaled version of an image using BrawlLib's texture converter.
 /// </summary>
 public static Bitmap Resize(Bitmap orig, Size resizeTo)
 {
     return orig.Resize(resizeTo.Width, resizeTo.Height);
 }
예제 #12
0
        public async Task<string[]> EvaluateCustomDNN(string imageUrl)
        {
            string domainBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string workingDirectory = Environment.CurrentDirectory;

            try
            {
                // This example requires the RestNet_18 model.
                // The model can be downloaded from <see cref="https://www.cntk.ai/resnet/ResNet_18.model"/>
                int numThreads = 1;
                List<float> outputs;

                using (var model = new IEvaluateModelManagedF())
                {
                    // initialize the evaluation engine
                    // TODO: initializing the evaluation engine should be one only once at the beginning
                    var initParams = string.Format("numCPUThreads={0}", numThreads);
                    model.Init(initParams);

                    // load the model
                    string modelFilePath = Path.Combine(domainBaseDirectory, @"CNTK\Models\ResNet_18.model");
                    var modelOption = string.Format("modelPath=\"{0}\"", modelFilePath);
                    model.CreateNetwork(modelOption, deviceId: -1);

                    // Prepare input value in the appropriate structure and size
                    var inDims = model.GetNodeDimensions(NodeGroup.Input);
                    if (inDims.First().Value != 224 * 224 * 3)
                    {
                        throw new CNTKRuntimeException(string.Format("The input dimension for {0} is {1} which is not the expected size of {2}.", inDims.First(), inDims.First().Value, 224 * 224 * 3), string.Empty);
                    }

                    // Transform the image
                    System.Net.Http.HttpClient httpClient = new HttpClient();
                    Stream imageStream = await httpClient.GetStreamAsync(imageUrl);
                    Bitmap bmp = new Bitmap(Bitmap.FromStream(imageStream));

                    var resized = bmp.Resize(224, 224, true);
                    var resizedCHW = resized.ParallelExtractCHW();
                    var inputs = new Dictionary<string, List<float>>() { { inDims.First().Key, resizedCHW } };

                    // We can call the evaluate method and get back the results (single layer output)...
                    var outDims = model.GetNodeDimensions(NodeGroup.Output);
                    outputs = model.Evaluate(inputs, outDims.First().Key);
                }

                List<string> o = new List<string>();

                foreach (float f in outputs)
                {
                    o.Add(f.ToString());
                }

                return o.ToArray<string>();
            }
            catch (Exception ex)
            {
                return new string[] { string.Format("domainBase directory {0}, workingDirectory {1}, exception details: {2}.", domainBaseDirectory, workingDirectory, ex.ToString()) };
            }
        }
예제 #13
0
 protected override void GetImage(out Bitmap bac)
 {
     if (TEXT.IndexOf("Blade") != -1 || TEXT.IndexOf("Swashplate") != -1)
     {
         double time = Game.TIME;
         double angle = time;
         if (TEXT.IndexOf("Blade") != -1)
         {
             double limit = UpgradeInfo.DataBase.BladeUpgradeValues[INDEX];
             if (limit != double.MaxValue)
             {
                 angle %= 2.0 * limit;
                 if (angle > limit) angle = 2.0 * limit - angle;
                 angle -= 0.5 * limit;
             }
             angle *= 2.0;
         }
         else if (TEXT.IndexOf("Swashplate") != -1)
         {
             angle = 0.5 * Math.Cos(Math.PI * time / UpgradeInfo.DataBase.SwashplateUpgradeValues[INDEX]) * Math.PI;
         }
         Bitmap bmp = Pod_Frame.Pod.GenerateImage(angle, Math.PI * Game.TIME);
         BITMAP.New(out bac,50, 50, Color.FromArgb(0, 0, 128));
         bac.Paste(bmp, bac.Half() - bmp.Half(), ImagePasteMode.Transparent);
         bac = bac.Resize(2.0);
         BitmapData data_bac = bac.GetBitmapData();
         DrawLOCKED(data_bac);
         bac.UnlockBits(data_bac);
     }
     else
     {
         Bitmap bmp; base.GetImage(out bmp);
         BITMAP.New(out bac,bmp.Width, bmp.Height, Color.FromArgb(0, 0, 128));
         bac.Paste(bmp, new Point(0, 0), ImagePasteMode.Transparent);
     }
 }
예제 #14
0
 protected override void GetImage(out Bitmap bmp)
 {
     bmp=ITEM[ITEM_EQUIPPED].GET_IMAGE();bmp=bmp.Resize(GetSize());
     BitmapData data_bmp = bmp.GetBitmapData();
     DrawLOCKED(data_bmp);
     bmp.UnlockBits(data_bmp);
 }
예제 #15
0
        public void ImportFromBitmap(Bitmap bitmap, CompressionMethod compression = CompressionMethod.RLE)
        {
            if (bitmap.Width <= 32 || bitmap.Height <= 32) { bitmap = bitmap.Resize(64, 64); }

            width = bitmap.Width;
            height = bitmap.Height;

            int planeCount = 4;// Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;

            if (bitmap.Width < 8 && bitmap.Height < 8) { planeCount = 1; }

            BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            byte[] iB = new byte[4 * bmpdata.Width * bmpdata.Height];
            Marshal.Copy(bmpdata.Scan0, iB, 0, bmpdata.Stride * bmpdata.Height);
            bitmap.UnlockBits(bmpdata);

            Parallel.For(0, planeCount,
                i =>
                //for (int i = 0; i < planeCount; i++)
                {
                    var plane = new Plane(i);
                    plane.Data = iB.ToList().Every(planeCount, i).ToArray();
                    plane.Compress(planeCount > 1 ? compression : CompressionMethod.None);
                    planes.Add(plane);
                }
            );

            switch (planeCount)
            {
                case 1:
                    planeFormat = PlaneFormat.Format1planeARGB;
                    break;

                case 3:
                    planeFormat = PlaneFormat.Format4planeXRGB;
                    break;

                case 4:
                    planeFormat = PlaneFormat.Format4planeARGB;
                    break;
            }
        }
 private static Bitmap CreateSidebarImage(Bitmap source)
 {
     return source.Resize(46, 46);
 }
예제 #17
0
        public ActionResult Upload(string qqfile)
        {
            try
            {
                var stream = Request.InputStream;
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase postedFile = Request.Files[0];
                    stream = postedFile.InputStream;
                }

                string fileUrl = _logoManager.GetPath("img" + DateTime.Now.Ticks + ".jpg");

                var image = new Bitmap(stream);
                image = image.Resize(150, 1024);
                image.SaveJpeg(Server.MapPath(fileUrl), 90);

                return Json(new { imageUrl = fileUrl });
            }
            catch (Exception ex)
            {
                return Json(new { imageUrl = _logoManager.GetPath(String.Empty) });
            }
        }
예제 #18
0
파일: GameData.cs 프로젝트: lluk/LoLy
 private static Bitmap GetPortrait(string path)
 {
     var portrait = new Bitmap(path);
     portrait = portrait.Clone(new Rectangle(10, 12, 103, 100), PixelFormat.Format24bppRgb);
     portrait = portrait.Resize(new Size(50, 50), false) as Bitmap;
     return portrait;
 }
예제 #19
0
 private static Bitmap CreateGankImage(Bitmap source)
 {
     return source.Resize(24, 24);
 }
        public void ResizeWithWidthIsGreaterThanImageWidthThrowsArgumentOutOfRangeException(int invalidWidth)
        {
            // Arrange
            var image = new Bitmap(1, 1);

            // Act

            // Assert
            Assert.Throws<ArgumentOutOfRangeException>(() => image.Resize(invalidWidth));
        }
예제 #21
0
파일: Program.cs 프로젝트: Microsoft/CNTK
        //
        // The example shows
        // - how to load model.
        // - how to prepare input data for a signle sample, a batch of samples in dense format.
        // - how to prepare input and output data map
        // - how to evaluate a model
        // - how to retrieve evaluation result and retrieve output data in dense format.
        //
        static void EvaluationWithDenseData(DeviceDescriptor device)
        {
            const string outputName = "Plus2060_output";

            // Load the model.
            Function modelFunc = Function.LoadModel("z.model");

            // Get output variable based on name
            Variable outputVar = modelFunc.Outputs.Where(variable => string.Equals(variable.Name, outputName)).Single();

            // Get input variable. The model has only one single input.
            // The same way described above for output variable can be used here to get input variable by name.
            Variable inputVar = modelFunc.Arguments.Single();

            // Get shape data for the input variable
            NDShape inputShape = inputVar.Shape;
            uint imageWidth = inputShape[0];
            uint imageHeight = inputShape[1];
            uint imageChannels = inputShape[2];
            uint imageSize = inputShape.TotalSize;

            var outputDataMap = new Dictionary<Variable, Value>();

            // Use case 1: Evaluate with single image
            Console.WriteLine("Evaluate single image");

            // Image preprocessing to match input requirements of the model.
            Bitmap bmp = new Bitmap(Bitmap.FromFile("00000.png"));
            var resized = bmp.Resize((int)imageWidth, (int)imageHeight, true);
            List<float> resizedCHW = resized.ParallelExtractCHW();

            // Create input data map
            var inputDataMap = new Dictionary<Variable, Value>();
            var inputVal = Value.CreateBatch(inputVar.Shape, resizedCHW, device);
            inputDataMap.Add(inputVar, inputVal);

            // Create ouput data map. Using null as Value to indicate using system allocated memory.
            // Alternatively, create a Value object and add it to the data map.
            outputDataMap.Add(outputVar, null);

            // Start evaluation on the device
            modelFunc.Evaluate(inputDataMap, outputDataMap, device);

            // Get evaluate result as dense output
            var outputData = new List<List<float>>();
            Value outputVal = outputDataMap[outputVar];
            outputVal.CopyTo(outputVar.Shape, outputData);

            // Use case 2: Evaluate with batch of images
            Console.WriteLine("Evaluate batch of images");

            var fileList = new List<string>() { "00000.png", "00001.png", "00002.png" };
            var seqData = new List<float>();
            for (int sampleIndex = 0; sampleIndex < fileList.Count; sampleIndex++)
            {
                bmp = new Bitmap(Bitmap.FromFile(fileList[sampleIndex++]));
                resized = bmp.Resize((int)imageWidth, (int)imageHeight, true);
                resizedCHW = resized.ParallelExtractCHW();
                // Aadd this sample to the data buffer.
                seqData.AddRange(resizedCHW);
            }

            // Create Value for the batch data.
            inputVal = Value.CreateBatch(inputVar.Shape, seqData, device);

            // Create input and output data map.
            inputDataMap[inputVar] = inputVal;
            outputDataMap[outputVar] = null;

            // Evaluate the model against the batch input
            modelFunc.Evaluate(inputDataMap, outputDataMap, device);

            // Retrieve the evaluation result.
            outputData = new List<List<float>>();
            outputVal = outputDataMap[outputVar];
            outputVal.CopyTo(outputVar.Shape, outputData);

            // Output result
            Console.WriteLine("The number of sequences in the batch: " + outputData.Count);
            int seqNo = 0;
            uint outputSampleSize = outputVar.Shape.TotalSize;
            foreach(var seq in outputData)
            {
                Console.WriteLine(String.Format("Sequence {0} contains {1} samples.", seqNo++, seq.Count/outputSampleSize));
                uint i = 0;
                uint sampleNo = 0;
                foreach (var element in seq)
                {
                    Console.Write(String.Format("    sample {0}: " + sampleNo));
                    Console.Write(element);
                    if (++i % outputSampleSize == 0)
                    {
                        Console.WriteLine(".");
                        sampleNo++;
                    }
                    else
                        Console.WriteLine(",");
                }
            }
        }
예제 #22
0
 static Bitmap Get_Image()
 {
     Bitmap ans;
     using (Bitmap bmp = new Bitmap(FULL))
     {
         Point p = new Point(0, ((1.0 - RATIO) * bmp.Height).Round());
         Size sz = new Size(bmp.Width, bmp.Height - p.Y);
         using (Bitmap bac = new Bitmap(EMPTY))
         {
             BitmapData data_bac = bac.GetBitmapData();
             data_bac.Paste(bmp, new Point(0, 0), ImagePasteMode.Transparent, new Rectangle(p, sz));
             data_bac.Add_RGB(-(BLACK_VALUE * 100.0).Round());
             double healthratio = VALUE / MAXIMUM;
             string text = (healthratio * 100.0).ToString("F2") + " %";
             Color textcolor = Color.FromArgb(0, 255, 0).Merge(Color.FromArgb(0, 0, 0), BLACK_VALUE);
             using (Font font = new Font("微軟正黑體", 14, FontStyle.Bold))
             {
                 data_bac.Paste(text, data_bac.Half(), textcolor, font, StringAlign.Middle, StringRowAlign.Middle);
             }
             bac.UnlockBits(data_bac);
             ans = bac.Resize(SIZE_RATIO);
         }
     }
     return ans;
 }