Search code examples
c#image-processingopencvemgucv

Sharpen Image Filter


I have code that takes an image saved on my computer and processes into a grayscale, smoothed gray, and canny edge image. What I would like it to do is sharpen the image by adding some type of filter to the image and then convert to gray and canny edge frame. I believe I have the code correct but when I run the program it doesn't seem to do anything different. Is the sharpen image in the wrong place? Is it somehow getting overlooked? Any suggestions please let me know.

      private void ProcessFrame()
  {
      String fileName = @"C:\filename";

               **Sharpen Image Filter code**
  public static Bitmap sharp(Bitmap img)
  {
      Bitmap sharpenImage = new Bitmap(img.Width, img.Height);

      int filterWidth = 3;
      int filterHeight = 3;
      int w = img.Width;
      int h = img.Height;

      double[,] filter = new double[filterWidth, filterHeight];

      filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = 
     filter[2,0]   =  filter[2, 1] = filter[2, 2] = -1;
      filter[1, 1] = 9;

      double factor = 1.0;
      double bias = 0.0;

      Color[,] result = new Color[img.Width, img.Height];

      for (int x = 0; x < w; ++x)
      {
          for (int y = 0; y < h; ++y)
          {
              double red = 0.0, green = 0.0, blue = 0.0;


              for (int filterX = 0; filterX < filterWidth; filterX++)
              {
                  for (int filterY = 0; filterY < filterHeight; filterY++)
                  {
                      int imageX = (x - filterWidth / 2 + filterX + w) % w;
                      int imageY = (y - filterHeight / 2 + filterY + h) % h;

                      Color imageColor = img.GetPixel(imageX, imageY);
                      red += imageColor.R * filter[filterX, filterY];
                      green += imageColor.G * filter[filterX, filterY];
                      blue += imageColor.B * filter[filterX, filterY];
                  }
                  int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
                  int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
                  int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);

                  result[x, y] = Color.FromArgb(r, g, b);
              }
          }
      }
      for (int i = 0; i < w; ++i)
      {
          for (int j = 0; j < h; ++j)
          {
              sharpenImage.SetPixel(i, j, result[i, j]);
          }
      }
      return sharpenImage;
  } 

**Sharpen Image Code Ends**

Solution

  • I guess I could be missing it, but it doesn't look like you are ever invoking your sharpening code on an image. That would certainly explain why the result isn't changing!