Exemplo n.º 1
0
        public string scanAreaForLetter(Bitmap area, string letter)
        {
            DateTime methodCall           = DateTime.Now;
            ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(TEMPLATE_MATCHING_SIMILARITY);

            Bitmap letterPic = getBitmapForLetter(letter);

            //Resizing
            letterPic = new AForge.Imaging.Filters.ResizeNearestNeighbor(letterPic.Width / LETTER_RESIZE_FACTOR, letterPic.Height / LETTER_RESIZE_FACTOR).Apply(letterPic);
            area      = new AForge.Imaging.Filters.ResizeNearestNeighbor(area.Width / BUTTON_RESIZE_FACTOR, area.Height / BUTTON_RESIZE_FACTOR).Apply(area);

            DateTime beforeProcessing = DateTime.Now;

            TemplateMatch[] matches = tm.ProcessImage(area, letterPic);

            TimeSpan resizingTime       = beforeProcessing - methodCall;
            TimeSpan processingTime     = DateTime.Now - beforeProcessing;
            TimeSpan totalOperationTime = DateTime.Now - methodCall;

            Console.WriteLine("Resizing completed in {0:F4} seconds", resizingTime.TotalSeconds);
            Console.WriteLine("Image processing completed in {0:F4} seconds", processingTime.TotalSeconds);
            Console.WriteLine("Operation completed in {0:F4} seconds", totalOperationTime.TotalSeconds);

            string result = "";

            if (matches.Length > 0)
            {
                Console.WriteLine("\nMatch was made for letter {0}!\n", letter);
                foreach (TemplateMatch match in matches)
                {
                    result += letter;
                }
            }
            else
            {
                Console.WriteLine("\nNo matches found for letter {0}.\n", letter);
            }

            return(result);
        }
        public Bitmap CreateMosaic(int grid_width, int grid_height, string sourceFolder, Bitmap original_img, bool ColourMosaic)
        {
            int original_width  = original_img.Width;
            int original_height = original_img.Height;

            //int grid_side = 30;
            int sub_image_width  = (int)(original_width / (double)grid_width);
            int sub_image_height = (int)(original_height / (double)grid_height);

            Console.WriteLine($"Sub image: {sub_image_width} x {sub_image_height}");
            Console.WriteLine($"Sub image pixels: {grid_width * sub_image_width} x {grid_height * sub_image_height} == {original_width} x {original_height}");

            AForge.Imaging.Filters.ResizeNearestNeighbor resize    = new AForge.Imaging.Filters.ResizeNearestNeighbor(sub_image_width, sub_image_height);
            AForge.Imaging.Filters.Grayscale             grayscale = new AForge.Imaging.Filters.Grayscale(1 / 3.0, 1 / 3.0, 1 / 3.0);

            string[] files = Directory.GetFiles(sourceFolder);

            Bitmap   combined_image = new Bitmap(original_width, original_height);
            Graphics g = Graphics.FromImage(combined_image);

            Bitmap original_gray = grayscale.Apply(original_img);

            Bitmap[] original_slices = new Bitmap[grid_width * grid_height];
            for (int i = 0; i < grid_width; i++)
            {
                for (int j = 0; j < grid_height; j++)
                {
                    if (CancelProcessing)
                    {
                        return(null);
                    }
                    Rectangle rect = new Rectangle(i * sub_image_width, j * sub_image_height, sub_image_width, sub_image_height);
                    AForge.Imaging.Filters.Crop crop_region = new AForge.Imaging.Filters.Crop(rect);
                    Bitmap slice = (ColourMosaic == true) ? crop_region.Apply(original_img) : crop_region.Apply(original_gray);
                    original_slices[i * grid_width + j] = slice;
                }
            }

            Bitmap[] candidates = new Bitmap[files.Length];
            for (int i = 0; i < candidates.Length; i++)
            {
                if (i % 100 == 0 || i + 100 > candidates.Length)
                {
                    int PercentComplete = (int)((100.0 * i) / candidates.Length);
                    Console.WriteLine($"Candidate preprocessing progress: {PercentComplete}%");
                    OnProcessingProgressChanged(new ProcessingProgressEventArgs()
                    {
                        PercentComplete = PercentComplete, ProcessingTask = "Preprocessing..."
                    });
                }

                if (CancelProcessing)
                {
                    return(null);
                }

                if (!IsImage(files[i]))
                {
                    continue;
                }

                Bitmap candidate_image = AForge.Imaging.Image.FromFile(files[i]);
                Bitmap candidate_gray;
                Bitmap resized_image;
                if (IsGrayScale(candidate_image) && false)
                {
                    if (ColourMosaic)
                    {
                        continue;
                    }

                    resized_image = resize.Apply(candidate_image);
                }
                else
                {
                    if (ColourMosaic)
                    {
                        resized_image = resize.Apply(candidate_image);
                    }
                    else
                    {
                        candidate_gray = grayscale.Apply(candidate_image);
                        resized_image  = resize.Apply(candidate_gray);
                    }
                }

                candidates[i] = resized_image;
            }

            List <int> used_indices = new List <int>();
            int        step         = 0;

            for (int i = 0; i < grid_width; i++)
            {
                for (int j = 0; j < grid_height; j++)
                {
                    if (CancelProcessing)
                    {
                        return(null);
                    }
                    int PercentComplete = (int)((100.0 * step) / (grid_width * grid_height - 1));
                    OnProcessingProgressChanged(new ProcessingProgressEventArgs()
                    {
                        PercentComplete = PercentComplete, ProcessingTask = "Creating mosaic..."
                    });
                    Console.WriteLine($"Finding best match to slice {step}/{grid_width * grid_height - 1}...");
                    int best_match_index = FindBestMatch(original_slices[step], candidates, used_indices);
                    used_indices.Add(best_match_index);
                    Bitmap sub_image = candidates[best_match_index];
                    int    cornerX   = i * sub_image_width;
                    int    cornerY   = j * sub_image_height;
                    g.DrawImage(sub_image, new Point(cornerX, cornerY));
                    step++;
                }
            }

            combined_image.Save("combined_image.jpg");

            return(combined_image);
        }
Exemplo n.º 3
0
        private Bitmap resize(Bitmap image, int newWidth, int newHeight)
        {
            if (KeepAspectRatio)
            {

                double ratio = (double)newHeight / (double)image.Height;
                newWidth = (int)((double)image.Width * ratio);

            }

            AForge.Imaging.Filters.Crop cropper = new AForge.Imaging.Filters.Crop(new Rectangle(0, 0, newWidth, newHeight));

            if (ScalingMethod == ScalingMethods.Nearest_Neighbor || ScalingMethod == ScalingMethods.Bicubic)
            {
                AForge.Imaging.Filters.ResizeNearestNeighbor resizer = new AForge.Imaging.Filters.ResizeNearestNeighbor(newWidth, newHeight);
                image = cropper.Apply(resizer.Apply((Bitmap)image));
            }
            if (ScalingMethod == ScalingMethods.Bicubic)
            {
                MessageBox.Show("Bicubic resize is not implimented for now.\nNReverting to nearest neighbor...");
                //AForge.Imaging.Filters.ResizeBicubic resizer = new AForge.Imaging.Filters.ResizeBicubic(newWidth, newHeight);
                //image = cropper.Apply(resizer.Apply((Bitmap)image));
            }
            if (ScalingMethod == ScalingMethods.Bilinear)
            {
                AForge.Imaging.Filters.ResizeBilinear resizer = new AForge.Imaging.Filters.ResizeBilinear(newWidth, newHeight);
                image = cropper.Apply(resizer.Apply((Bitmap)image));
            }

            return image;
        }
Exemplo n.º 4
0
      private void generateHeightData()
      {
          Logger.Debug("generateHeightData horizontal:{0}  useZ:{1}", rbEngravingPattern1.Checked, rBGrayZ.Checked);
          if (resultImage == null)
          {
              return;                                       //if no image, do nothing
          }
          cncPixelResoX = (float)nUDResoX.Value;            // resolution = distance between pixels / lines / columns
          cncPixelResoY = (float)nUDResoY.Value;
          float resoRatioYX = cncPixelResoY / cncPixelResoX;
          float penWidth    = cncPixelResoY;

          resultImage = new Bitmap(adjustedImage);  // adjustedImage is shown in preview, resultImage will be scanned

          if (rbEngravingPattern1.Checked)          // horizontal no change
          {
          }
          else if (rbEngravingPattern2.Checked)                  // if diagonal, take account of 45° angle
          {
              int factor = (int)Math.Round(resoRatioYX) + 1;
              resoRatioYX   = factor;
              cncPixelResoX = cncPixelResoY * 1.414f / factor;
              cncPixelResoY = cncPixelResoX;  // cncPixelResoY * 1.414f;
          }
          else
          {
              cncPixelResoY = cncPixelResoX;
          }

          int newWidth  = (int)((float)nUDWidth.Value / cncPixelResoX);
          int newHeigth = (int)((float)nUDHeight.Value / cncPixelResoY);

          AForge.Imaging.Filters.ResizeNearestNeighbor filterResize = new AForge.Imaging.Filters.ResizeNearestNeighbor(newWidth, newHeigth);
          resultImage = filterResize.Apply(adjustedImage);

          int pixelCount     = resultImage.Width * resultImage.Height;
          int pixelProcessed = 0;
          int percentDone    = 0;

          int  pixelPosY;                     // top/botom pixel
          int  pixelPosX;                     // Left/right pixel
          bool useZnotS = rBGrayZ.Checked;    // calculate Z-value or S-value
          bool backAndForth = !cBOnlyLeftToRight.Checked;
          bool relative = cBCompress.Checked; // true;
          bool firstValue, firstLine = true;

          int pixelValLast, pixelValNow, pixelValNext;      // gray-values at pixel pos

          cncCoordLastX = cncCoordX = pixelPosX = 0;
          cncCoordLastY = cncCoordY = pixelPosY = 0;

          if (rbEngravingPattern1.Checked)                                      // horizontal
          {
              generateGCodePreset(0, cncPixelResoY * (resultImage.Height - 1)); // gcode.setup, -jobStart, PenUp, -G0 to 1st pos.
          }
          else if (rbEngravingPattern2.Checked)
          {
              generateGCodePreset(0, 0);      // gcode.setup, -jobStart, PenUp, -G0 to 1st pos.
          }
          else
          {
              cncCoordLastX = cncCoordX = cncPixelResoX * resultImage.Width / 2;
              cncCoordLastY = cncCoordY = cncPixelResoY * resultImage.Height / 2;
              generateGCodePreset(cncCoordX, cncCoordY);
          }

          if (useZnotS)     // set 2D-View display option to translate S/Z value to pen width
          {
              gcode.Comment(finalString, string.Format("{0} Min=\"{1}\" Max=\"{2}\" Width=\"{3}\" />", xmlMarker.halftoneZ, nUDZTop.Value, nUDZBot.Value, penWidth));
          }
          else
          {
              gcode.Comment(finalString, string.Format("{0} Min=\"{1}\" Max=\"{2}\" Width=\"{3}\" />", xmlMarker.halftoneS, nUDSMin.Value, nUDSMax.Value, penWidth));
          }

          gcode.Comment(finalString, string.Format("{0} Id=\"{1}\" PenColor=\"black\" >", xmlMarker.figureStart, 1));
          finalString.AppendFormat("F{0}\r\n", gcode.gcodeXYFeed); // set feedrate

          if (rbEngravingPattern1.Checked)                         // horizontal
          {
              //Start image
              cncCoordLastX = cncCoordX = pixelPosX = 0;        //Left pixel
              pixelPosY     = resultImage.Height - 1;           //top tile
              cncCoordLastY = cncCoordY = cncPixelResoY * (float)pixelPosY;

              while (pixelPosY >= 0)    // line by line from top to bottom
              {
                  pixelPosX = 0;        // 1st line starts at 0
                  cncCoordX = cncPixelResoX * (float)pixelPosX;
                  cncCoordY = cncPixelResoY * (float)pixelPosY;
                  gcode.Comment(finalString, string.Format("{0} Y=\"{1}\">", xmlMarker.passStart, cncCoordY));

                  // move to first position in line
                  if (!backAndForth || (pixelPosY == (resultImage.Height - 1)))                // move line by line from left to right
                  {
                      if (relative)
                      {
                          finalString.AppendLine("G90");
                      }                                                   // switch to absolute
                      gcode.PenUp(finalString);
                      cncCoordLastZ = cncCoordZ = gcode.gcodeZUp;
                      gcode.MoveToRapid(finalString, cncCoordX, cncCoordY);
                      if (useZnotS)     // move servo down and delay
                      {
                          pixelValNow = pixelValNext = getPixelValue(pixelPosX, pixelPosY, useZnotS);
                          setCommand(pixelPosX, pixelPosY, pixelValNow, useZnotS, false);
                      }
                      else
                      {
                          finalString.AppendFormat("G{0} X{1} S{2}\r\n", gcode.frmtCode(1), gcode.frmtNum(-0.01), Math.Round(nUDSMin.Value));
                          finalString.AppendFormat("G{0} P{1}\r\n", gcode.frmtCode(4), gcode.frmtNum(Properties.Settings.Default.importGCPWMDlyUp));
                      }
                      cncCoordLastX = cncCoordX;
                      cncCoordLastY = cncCoordY;
                  }
                  // create horizontal data left to rigth, check current and next pixel for change in value to reduce gcode
                  if (relative)
                  {
                      finalString.AppendLine("G91G1");
                  }
                  pixelValLast = -1; pixelValNow = pixelValNext = getPixelValue(pixelPosX, pixelPosY, useZnotS);
                  while ((pixelPosX < (resultImage.Width - 1)) && (pixelPosY >= 0))     //From left to right
                  {
                      firstValue   = (pixelValLast < 0) && firstLine;
                      pixelValNext = getPixelValue(pixelPosX + 1, pixelPosY, useZnotS);
                      if ((pixelPosX == 0) || (pixelValNow != pixelValLast) || (pixelValNow != pixelValNext))
                      {
                          setCommand(pixelPosX, pixelPosY, pixelValNow, useZnotS, relative);
                      }
                      pixelValLast = pixelValNow; pixelValNow = pixelValNext;
                      pixelProcessed++; pixelPosX++;
                  }
                  setCommand(pixelPosX, pixelPosY, pixelValNow, useZnotS, relative);
                  pixelPosY--;
                  gcode.Comment(finalString, string.Format("{0}>", xmlMarker.passEnd));

                  // create horizontal data rigth to left
                  if (backAndForth && (pixelPosY >= 0))
                  {
                      gcode.Comment(finalString, string.Format("{0} Y=\"{1}\">", xmlMarker.passStart, cncCoordY));
                      pixelPosX = (resultImage.Width - 1);    // 2nd line starts far right
                      setCommand(pixelPosX, pixelPosY, pixelValNow, useZnotS, relative);
                      pixelValLast = -1; pixelValNow = pixelValNext = getPixelValue(pixelPosX, pixelPosY, useZnotS);
                      while ((pixelPosX > 0) && (pixelPosY >= 0))       //From right to left
                      {
                          pixelValNext = getPixelValue(pixelPosX - 1, pixelPosY, useZnotS);
                          if ((pixelPosX == (resultImage.Width - 1)) || (pixelValNow != pixelValLast) || (pixelValNow != pixelValNext))
                          {
                              setCommand(pixelPosX, pixelPosY, pixelValNow, useZnotS, relative);
                          }
                          pixelValLast = pixelValNow; pixelValNow = pixelValNext;
                          pixelProcessed++; pixelPosX--;
                      }
                      setCommand(pixelPosX, pixelPosY, pixelValNow, useZnotS, relative);
                      pixelPosY--;
                      gcode.Comment(finalString, string.Format("{0}>", xmlMarker.passEnd));
                      firstLine = false;
                  }

                  percentDone    = (pixelProcessed * 100) / pixelCount;
                  lblStatus.Text = "Generating GCode... " + Convert.ToString(percentDone) + "%";
                  if ((percentDone % 10) == 0)
                  {
                      Refresh();
                  }
              }
          }
          else if (rbEngravingPattern2.Checked)          // diagonal
          {
              //Start image - diagonal up-left to bottom-right
              pixelPosX = 0;
              pixelPosY = 0;
              if (relative)
              {
                  finalString.AppendLine("G91G1");
              }
              while ((pixelPosX < resultImage.Width) | (pixelPosY < resultImage.Height))
              {
                  while ((pixelPosX < resultImage.Width) & (pixelPosY >= 0))                        // top-left to bot-right
                  {
                      pixelValNext = getPixelValue(pixelPosX - 1, pixelPosY, useZnotS);
                      { setCommand(pixelPosX, pixelPosY, pixelValNext, useZnotS, relative); }       // scan with 1px reso
                      pixelProcessed++; pixelPosX++; pixelPosY--;
                  }
                  pixelPosX--; pixelPosY++;     // loop did one too much

                  if (pixelPosX >= resultImage.Width - 1)
                  {
                      pixelPosY += (int)resoRatioYX;                                          // next line distance is higher  pixelPosY++;
                  }
                  else
                  {
                      pixelPosX += (int)resoRatioYX;                          // ++
                  }
                  while ((pixelPosX >= 0) & (pixelPosY < resultImage.Height)) // bot-rigth to top-left
                  {
                      pixelValNext = getPixelValue(pixelPosX - 1, pixelPosY, useZnotS);
                      { setCommand(pixelPosX, pixelPosY, pixelValNext, useZnotS, relative); }
                      pixelProcessed++; pixelPosX--; pixelPosY++;
                  }
                  pixelPosX++; pixelPosY--;     // loop did one too much

                  if (pixelPosY >= resultImage.Height - 1)
                  {
                      pixelPosX += (int)resoRatioYX;                                           //++
                  }
                  else
                  {
                      pixelPosY += (int)resoRatioYX;       //++
                  }
                  percentDone    = (pixelProcessed * 100) / pixelCount;
                  lblStatus.Text = "Generating GCode... " + Convert.ToString(percentDone) + "%";
                  if ((percentDone % 10) == 0)
                  {
                      Refresh();
                  }
              }
          }
          else if (rbEngravingPattern3.Checked)          // spiral
          {
              createSpiral((float)nUDResoY.Value, cncPixelResoX, resultImage.Width);
              createScanPath(resultImage.Width, resultImage.Height, resultImage.Width / 2, resultImage.Height / 2);
              applyScanPath(useZnotS, relative);
          }
          else
          {
              createFrom2DView(cncPixelResoX);
              createScanPath(resultImage.Width, resultImage.Height, 0, 0);
              applyScanPath(useZnotS, relative);
          }


          if (relative)
          {
              finalString.AppendLine("G90");
          }
          gcode.Comment(finalString, string.Format("{0}>", xmlMarker.figureEnd));
          gcode.jobEnd(finalString);
          if (rBGrayS.Checked && cBLaserModeOffEnd.Checked)
          {
              finalString.AppendLine("$32=0 (Lasermode off)");
          }

          imagegcode  = "( Generated by GRBL-Plotter )\r\n";
          imagegcode += gcode.GetHeader("Image import") + finalString.Replace(',', '.').ToString() + gcode.GetFooter();
      }
Exemplo n.º 5
0
        private Bitmap resize(Bitmap image, int newWidth, int newHeight)
        {
            if (keepAspectRatio)
            {

                double ratio = (double)newHeight / (double)image.Height;
                newWidth = (int)((double)image.Width * ratio);

            }

            AForge.Imaging.Filters.Crop cropper = new AForge.Imaging.Filters.Crop(new Rectangle(0, 0, newWidth, newHeight));

            if (cmbScalingMethod.SelectedIndex == 0)
            {
                AForge.Imaging.Filters.ResizeNearestNeighbor resizer = new AForge.Imaging.Filters.ResizeNearestNeighbor(newWidth, newHeight);
                image = cropper.Apply(resizer.Apply((Bitmap)image));
            }
            if (cmbScalingMethod.SelectedIndex == 1)
            {
                AForge.Imaging.Filters.ResizeBicubic resizer = new AForge.Imaging.Filters.ResizeBicubic(newWidth, newHeight);
                image = cropper.Apply(resizer.Apply((Bitmap)image));
            }
            if (cmbScalingMethod.SelectedIndex == 2)
            {
                AForge.Imaging.Filters.ResizeBilinear resizer = new AForge.Imaging.Filters.ResizeBilinear(newWidth, newHeight);
                image = cropper.Apply(resizer.Apply((Bitmap)image));
            }

            return image;
        }
Exemplo n.º 6
0
 /// <summary>
 /// Resize raw image to specified size
 /// </summary>
 /// <param name="ui">UnmanagedImage - raw image</param>
 /// <param name="w">int - new width</param>
 /// <param name="h">int - new height</param>
 /// <returns>UnmanagedImage - resized</returns>
 public static UnmanagedImage ResizeTo(this UnmanagedImage ui, int w, int h)
 {
     AForge.Imaging.Filters.ResizeNearestNeighbor resize = new AForge.Imaging.Filters.ResizeNearestNeighbor(w, h);
     return(resize.Apply(ui));
 }
Exemplo n.º 7
0
        public void LoadImage(System.Drawing.Image image)
        {
            currentImage = image;
            Graphics g = this.CreateGraphics();
            g.Clear(Color.White);
            double ratio = ((double)image.Width / (double)this.Width);

            Bitmap overlay = new Bitmap(image.Width, image.Height);
            Graphics gOverlay = Graphics.FromImage(overlay);

            int newWidth = (int)((double)image.Width / ratio);
            int newHeight = (int)((double)image.Height / ratio);

            if (drawInputGroupOverlay)
            {

                if (inputGroupType == InputGroupType.Horozontal || inputGroupType == InputGroupType.Grid)
                {

                    for (int i = 1; i < segments; i++)
                    {
                        gOverlay.DrawLine(new Pen(Brushes.Red, 0.5f), 0, (int)Math.Round((double)i * ((double)image.Height / (double)segments)), image.Width, (int)Math.Round((double)i * ((double)image.Height / (double)segments)));

                    }

                }

                if (inputGroupType == InputGroupType.Vertical || inputGroupType == InputGroupType.Grid)
                {

                    for (int i = 1; i < segments; i++)
                    {
                        gOverlay.DrawLine(Pens.Red, (int)Math.Round((double)i * ((double)image.Width / (double)segments)), 0, (int)Math.Round((double)i * ((double)image.Width / (double)segments)), image.Height);

                    }

                }

            }

            if( scalingMethod == ENFORM.Core.ScalingMethods.Bicubic)
            {
                MessageBox.Show("Not implimented yet, reverting to nearest neighbor...");
                /*
                scalingMethod = ENFORM.ScalingMethod.Nearest_Neighbor;
                AForge.Imaging.Filters.ResizeBicubic resize = new AForge.Imaging.Filters.ResizeBicubic(newWidth, newHeight);
                g.DrawImage(resize.Apply((Bitmap)image), new Point(0, 0));
                g.DrawImage(resize.Apply((Bitmap)overlay), new Point(0, 0));
                 * */
                scalingMethod = ENFORM.Core.ScalingMethods.Nearest_Neighbor;
            }
            if (scalingMethod == ENFORM.Core.ScalingMethods.Bilinear)
            {
                AForge.Imaging.Filters.ResizeBilinear resize = new AForge.Imaging.Filters.ResizeBilinear(newWidth, newHeight);
                g.DrawImage(resize.Apply((Bitmap)image), new Point(0, 0));
                g.DrawImage(resize.Apply((Bitmap)overlay), new Point(0, 0));
            }
            if (scalingMethod == ENFORM.Core.ScalingMethods.Nearest_Neighbor)
            {
                AForge.Imaging.Filters.ResizeNearestNeighbor resize = new AForge.Imaging.Filters.ResizeNearestNeighbor(newWidth, newHeight);
                g.DrawImage(resize.Apply((Bitmap)image), new Point(0, 0));
                AForge.Imaging.Filters.ResizeNearestNeighbor resizeB = new AForge.Imaging.Filters.ResizeNearestNeighbor(newWidth, newHeight);
                g.DrawImage(resizeB.Apply((Bitmap)overlay), new Point(0, 0));
            }

            //g.DrawImage(resize.Apply((Bitmap)image), new Point(0,0));
               // g.DrawImage(resize.Apply((Bitmap)overlay), new Point(0,0));

            editable = true;
        }