Author: saqibkhan

  • Create Zooming Effect

    Zooming is the process of enlarging an image so that the details in the image become more visible and prominent.

    We use OpenCV function resize to apply zooming to images. It can be found under Imgproc package. Its syntax is given below −

    Imgproc.resize(source,destination, destination.size(),zoomFactor,zoomFactor,Interpolation);
    

    In the resize function, we pass source image, destination image and its size, zooming factor, and the interpolation method to use.

    The interpolation methods available are described below −

    Sr.No.Interpolation method & Description
    1INTER_NEARESTIt is nearest-neighbour interpolation.
    2INTER_LINEARIt is bilinear interpolation (used by default).
    3INTER_AREAIt is resampling using pixel area relation. It may be a preferred method for image decimation, as it gives more-free results.
    4INTER_CUBICIt is a bi-cubic interpolation over 4×4 pixel neighbourhood.
    5INTER_LANCZOS4It is a Lanczos interpolation over 8×8 pixel neighbourhood.

    Apart from the resize method, there are other methods provided by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to apply zooming to an image.

    import org.opencv.core.Core;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class Main {
       public static void main( String[] args ) {
       
    
      try {
         int zoomingFactor = 2;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("image.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows() * zoomingFactor, source.cols()*  zoomingFactor,source.type());  
         
         Imgproc.resize(source, destination, destination.size(),  zoomingFactor,zoomingFactor,Imgproc.INTER_NEAREST);
         Highgui.imwrite("zoomed.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("Error: "+e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Create Zooming Effect Tutorial

    Zoomed Image(Zooming factor − 2)

    Create Zooming Effect Tutorial
  • Weighted Average Filter

    In weighted average filter, we gave more weight to the center value, due to which the contribution of center becomes more than the rest of the values. Due to weighted average filtering, we can control the blurring of image.

    We use OpenCV function filter2D to apply weighted average filter to images. It can be found under Imgproc package. Its syntax is given below −

    filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );
    

    The function arguments are described below −

    Sr.No.Argument & Description
    1srcIt is source image.
    2dstIt is destination image.
    3ddepthIt is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
    4kernelIt is the kernel to be scanned through the image.
    5anchorIt is the position of the anchor relative to its kernel. The location Point(-1, -1) indicates the center by default.
    6deltaIt is a value to be added to each pixel during the convolution. By default it is 0.
    7BORDER_DEFAULTWe let this value by default.

    Apart from the filter2D() method, there are other methods provide by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to apply weighted average filter to an image of Graycale.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class convolution {
       public static void main( String[] args ) {
       
    
      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = Mat.ones(kernelSize,kernelSize, CvType.CV_32F) {	      
         
         for(int i=0; i<kernel.rows(); i++) {
            for(int j=0; j<kernel.cols(); j++) {
               double[] m = kernel.get(i, j);
               for(int k =0; k<m.length; k++) {
                  if(i==1 && j==1) {
                     m[k] = 10/18;
                  }
                  else{
                     m[k] = m[k]/(18);
                  }
               }
               kernel.put(i,j, m);
               }
            }	
         };	      
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("output.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying Weighted Average Filter Tutorial

    This original image is convolved with the weighted average filter as given below −

    Weighted Average Filter

    111
    1101
    111

    Convolved Image

    Applying Weighted Average Filter Tutorial
  • Laplacian Operator

    Laplacian Operator is also a derivative operator which is used to find edges in an image. The major difference between Laplacian and other operators like Prewitt, Sobel, Robinson, and Kirsch is that these all are first order derivative masks but Laplacian is a second order derivative mask.

    We use OpenCV function filter2D to apply Laplacian operator to images. It can be found under Imgproc package. Its syntax is given below −

    filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );
    

    The function arguments are described below −

    Sr.No.Arguments
    1srcIt is source image.
    2dstIt is destination image.
    3depthIt is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
    4kernelIt is the kernel to be scanned through the image.
    5anchorIt is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default.
    6deltaIt is a value to be added to each pixel during the convolution. By default it is 0.
    7BORDER_DEFAULTWe let this value by default.

    Apart from the filter2D() method, there are other methods provided by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to apply Laplacian operator to an image of Grayscale.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class convolution {
       public static void main( String[] args ) {
       
    
      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,0);
               put(0,1,-1)
               put(0,2,0);
               put(1,0-1);
               put(1,1,4);
               put(1,2,-1);
               put(2,0,0);
               put(2,1,-1);
               put(2,2,0);
            }
         };	      
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("output.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying Laplacian operator Tutorial

    This original image is convolved with the Laplacian Negative operator as given below −

    Laplacian Negative

    0-10
    -14-1
    0-10

    Convolved Image(Laplacian Negative)

    Applying Laplacian operator Tutorial

    This original image is convolved with the Laplacian Positive operator as given below −

    Laplacian Positive

    010
    1-41
    010

    Convolved Image (Laplacian Positive)

    Applying Laplacian operator Tutorial
  • Robinson Operator

    Robinson compass masks are yet another type of derivative masks which are used for edge detection. This operator is also known as direction mask. In this operator we take one mask and rotate it in all the eight major directions to get edges of the eight directions.

    We are going to use OpenCV function filter2D to apply Robinson operator to images. It can be found under Imgproc package. Its syntax is given below −

    filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );
    

    The function arguments are described below −

    Sr.No.Argument & Description
    1srcIt is source image.
    2dstIt is destination image.
    3depthIt is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
    4kernelIt is the kernel to be scanned through the image.
    5anchorIt is the position of the anchor relative to its kernel. The location Point(-1, -1) indicates the center by default.
    6deltaIt is a value to be added to each pixel during the convolution. By default it is 0.
    7BORDER_DEFAULTWe let this value by default.

    Apart from the filter2D method, there are other methods provided by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to apply Robinson operator to an image of Grayscale.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class convolution {
       public static void main( String[] args ) {
       
    
      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,-1);
               put(0,1,0);
               put(0,2,1);
               put(1,0-2);
               put(1,1,0);
               put(1,2,2);
               put(2,0,-1);
               put(2,1,0);
               put(2,2,1);
            }
         };	      
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("output.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying Robinson operator Tutorial

    This original image is convolved with the Robinson operator of North edges as given below −

    North Direction Mask

    -101
    -202
    -101

    Convolved Image(Robinson North)

    Applying Robinson operator Tutorial

    This original image has also been convolved with the Robinson operator of East edges as given below −

    East Direction Mask

    -1-2-1
    000
    121

    Convolved Image(Robinson East)

    Applying Robinson operator Tutorial
  • Kirsch Operator

    Kirsch compass masks are yet another type of derivative mask which are used for edge detection. This operator is also known as direction mask. In this operator we take one mask and rotate it in all the eight compass directions to get edges of the eight directions.

    We are going to use OpenCV function filter2D to apply Kirsch operator to images. It can be found under Imgproc package. Its syntax is given below −

    filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );
    

    The function arguments are described below −

    Sr.No.Argument
    1srcIt is source image.
    2dstIt is destination image.
    3depthIt is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
    4kernelIt is the kernel to be scanned through the image.
    5anchorIt is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default.
    6deltaIt is a value to be added to each pixel during the convolution. By default it is 0.
    7BORDER_DEFAULTWe let this value by default.

    Apart from the filter2D() method, there are other methods provided by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to apply Kirsch operator to an image of Grayscale.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class convolution {
       public static void main( String[] args ) {
       
    
      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,-3);
               put(0,1,-3);
               put(0,2,-3);
      
               put(1,0-3);
               put(1,1,0);
               put(1,2,-3);
               put(2,0,5);
               put(2,1,5);
               put(2,2,5);
            }
         };	      
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("output.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying Kirsch operator Tutorial

    This original image is convolved with the Kirsch operator of East edges, which as given below −

    Kirsch East

    -3-3-3
    -30-3
    555

    Convolved Image(Kirsch East)

    Applying Kirsch operator Tutorial

    This original image is convolved with the Kirsch operator of South West edges, which as given below −

    Kirsch South West

    55-3
    50-3
    -3-3-3

    Convolved Image (Kirsch South West)

    Applying Kirsch operator Tutorial
  • Sobel Operator

    Sobel operator is very similar to Prewitt operator. It is also a derivative mask and is used for edge detection. Sobel operator is used to detect two kinds of edges in an image: Vertical direction edges and Horizontal direction edges.

    We are going to use OpenCV function filter2D to apply Sobel operator to images. It can be found under Imgproc package. Its syntax is given below −

    filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );
    

    The function arguments are described below −

    Sr.No.Argument
    1srcIt is source image.
    2dstIt is destination image.
    3depthIt is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
    4kernelIt is the kernel to be scanned through the image.
    5anchorIt is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default.
    6deltaIt is a value to be added to each pixel during the convolution. By default it is 0.
    7BORDER_DEFAULTWe let this value by default.

    Apart from the filter2D method, there are other methods provide by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to apply Sobel operator to an image of Grayscale.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class convolution {
       public static void main( String[] args ) {
       
    
      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,-1);
               put(0,1,0);
               put(0,2,1);
               put(1,0-2);
               put(1,1,0);
               put(1,2,2);
               put(2,0,-1);
               put(2,1,0);
               put(2,2,1);
            }
         };	      
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("output.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying Sobel operator Tutorial

    This original image is convolved with the Sobel operator of vertical edges, which is given below −

    Vertical Direction

    -101
    -202
    -101

    Convolved Image(Vertical Direction)

    Applying Sobel operator Tutorial

    This original is convolved with the Sobel operator of horizontal edges, which is given below −

    Horizontal Direction

    -1-2-1
    000
    121

    Convolved Image(Horizontal Direction)

    Applying Sobel operator Tutorial
  • Prewitt Operator

    Prewitt operator is used for edge detection in an image. It detects two types of edges: vertical edges and horizontal edges.

    We use OpenCV function filter2D to apply Prewitt operator to images. It can be found under Imgproc package. Its syntax is given below −

    filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );
    

    The function arguments are described below −

    Sr.No.Argument & Description
    1srcIt is source image.
    2dstIt is destination image.
    3depthIt is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
    4kernelIt is the kernel to be scanned through the image.
    5anchorIt is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default.
    6deltaIt is a value to be added to each pixel during the convolution. By default it is 0.
    7BORDER_DEFAULTWe let this value by default.

    Apart from the filter2D method, there are other methods provide by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to apply Prewitt operator to an image of Grayscale.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class convolution {
       public static void main( String[] args ) {
    
      try {
         int kernelSize = 9;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,-1);
               put(0,1,0);
               put(0,2,1);
               put(1,0-1);
               put(1,1,0);
               put(1,2,1);
               put(2,0,-1);
               put(2,1,0);
               put(2,2,1);
            }
         };	 
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("output.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying Prewitt operator Tutorial

    This original image is convolved with the Prewitt operator of vertical edges as given below −

    Vertical direction

    -101
    -101
    -101

    Convolved Image(Vertical Direction)

    Applying Prewitt operator Tutorial

    This original image has also been convolved with the Prewitt operator of horizontal edges, which is given below −

    Horizontal Direction

    -1-1-1
    000
    111

    Convolved Image(Horizontal Direction)

    Applying Prewitt operator Tutorial
  • Understand Convolution

    Convolution is a mathematical operation on two functions f and g. The function f and g in this case are images, since an image is also a two dimensional function.

    Performing Convolution

    In order to perform convolution on an image, following steps are taken −

    • Flip the mask (horizontally and vertically) only once.
    • Slide the mask onto the image.
    • Multiply the corresponding elements and then add them.
    • Repeat this procedure until all values of the image has been calculated.

    We use OpenCV function filter2D to apply convolution to images. It can be found under Imgproc package. Its syntax is given below −

    filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );
    

    The function arguments are described below −

    Sr.No.Argument & Description
    1srcIt is source image.
    2dstIt is destination image.
    3depthIt is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
    4kernelIt is the kernel to be scanned through the image.
    5anchorIt is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default.
    6deltaIt is a value to be added to each pixel during the convolution. By default it is 0.
    7BORDER_DEFAULTWe let this value by default.

    Example

    The following example demonstrates the use of Imgproc class to perform convolution on an image of Grayscale.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class convolution {
       public static void main( String[] args ) {
       
    
      try {
         int kernelSize = 3;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,0);
               put(0,1,0);
               put(0,2,0);
               put(1,0,0);
               put(1,1,1);
               put(1,2,0);
               put(2,0,0);
               put(2,1,0);
               put(2,2,0);
            }
         };
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("original.jpg", destination);
         
      } catch (Exception e) {
          System.out.println("Error:" + e.getMessage());
      }
    } }

    Output

    In this example we convolve our image with the following filter(kernel). This filter results in producing original image as it is −

    000
    010
    000

    Original Image

    Understand Convolution Tutorial

    Convolved Image

    Understand Convolution Tutorial
  • Applying Watermark

    In this chapter we learn two ways of applying watermark on images. These ways are −

    • Applying Text Watermark
    • Applying Image watermark

    Applying Text Watermark

    We use OpenCV function putText to apply text watermark to image. It can be found under Core package. Its syntax is given below −

    Core.putText(source, Text, Point, fontFace ,fontScale , color);
    

    The parameters of this function are described below −

    Sr.No.Parameter & Description
    1SourceIt is source image.
    2TextIt is the string text that would appear on the image.
    3PointIt is the point where text should appear on image.
    4fontFaceFont type. For example − FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_COMPLEX etc.
    5fontScaleIt is font scale factor that is multiplied by the font-specific base size.
    6colorIt is text color.

    Apart from the putText method, there are other methods provided by the Core class. They are described briefly −

    Sr.No.Method & Description
    1normalize(Mat src, Mat dst, double alpha, double beta, int norm_type)It normalizes the norm or value range of an array.
    2perspectiveTransform(Mat src, Mat dst, Mat m)It performs the perspective matrix transformation of vectors.
    3phase(Mat x, Mat y, Mat angle)It calculates the rotation angle of 2D vectors.
    4rectangle(Mat img, Point pt1, Point pt2, Scalar color)It draws a simple, thick, or filled up-right rectangle.
    5reduce(Mat src, Mat dst, int dim, int rtype, int dtype)It reduces a matrix to a vector.
    6transform(Mat src, Mat dst, Mat m)It performs the matrix transformation of every array element.

    Example

    The following example demonstrates the use of Core class to apply text watermark to an image −

    import org.opencv.core.Core;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class Main {
       public static void main( String[] args ) {
       
    
      try{
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         Mat source = Highgui.imread("digital_image_processing.jpg",  Highgui.CV_LOAD_IMAGE_COLOR);
         Mat destination = new Mat(source.rows(),source.cols(), source.type());  
         
         Core.putText(source, "Tutorialspoint.com", new Point  (source.rows()/2,source.cols()/2), Core.FONT_ITALIC,new Double(1),new  Scalar(255));
         Highgui.imwrite("watermarked.jpg", source);
         
      } catch (Exception e) {
         System.out.println("Error: "+e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying WaterMark Tutorial

    Text Watermarked Image

    Applying WaterMark Tutorial

    Applying Image Watermark on Image

    We are going to use OpenCV function addWeighted to apply image watermark to image. It can be found under Core package. Its syntax is given below −

    Core.addWeighted(InputArray src1, alpha, src2 (Watermark image), beta, gamma, OutputArray dst);
    

    The parameters of this function are described below −

    Sr.No.Parameter & Description
    1src1It is first input array.
    2alphaIt is the weight of the first array elements.
    3src2It is the second input array of the same size and channel number as src1.
    4betaIt is the weight of the second array elements.
    5gammaIt is the scalar added to each sum.
    6dstIt is the output array that has the same size and number of channels as the input arrays.

    Example

    The following example demonstrates the use of Core class to apply image watermark to an image −

    import org.opencv.core.Core;
    import org.opencv.core.Mat;
    
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class Main {
       public static void main( String[] args ) {
       
    
      try{
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("digital_image_processing.jpg",  Highgui.CV_LOAD_IMAGE_COLOR);
         Mat waterMark = Highgui.imread("watermark.png",  Highgui.CV_LOAD_IMAGE_COLOR);
         Rect ROI = new Rect(waterMark.rows() * 4,waterMark.cols(),  waterMark.cols(),waterMark.rows());
         
         Core.addWeighted(source.submat(ROI), 0.8, waterMark, 0.2, 1,  source.submat(ROI));
         Highgui.imwrite("watermarkedImage.jpg", source);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Applying WaterMark Tutorial

    The Watermark Image

    Applying WaterMark Tutorial

    Watermarked Image

    Applying WaterMark Tutorial
  • Eroding and Dilating

    In this chapter we learn apply two very common morphology operators:Dilation and Erosion.

    We use OpenCV function erode and dilate. They can be found under Imgproc package. Its syntax is given below −

    Imgproc.erode(source, destination, element);
    Imgproc.dilate(source, destination, element);				
    

    The parameters are described below −

    Sr.No.Parameter & Description
    1sourceIt is Source image.
    2destinationIt is destination image.
    3elementIt is a structuring element used for erosion and dilation, if element=Mat(), a 3 x 3 rectangular structuring element is used.

    Apart from erode() and dilate() methods, there are other methods provided by the Imgproc class. They are described briefly −

    Sr.No.Method & Description
    1cvtColor(Mat src, Mat dst, int code, int dstCn)It converts an image from one color space to another.
    2dilate(Mat src, Mat dst, Mat kernel)It dilates an image by using a specific structuring element.
    3equalizeHist(Mat src, Mat dst)It equalizes the histogram of a grayscale image.
    4filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)It convolves an image with the kernel.
    5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)It blurs an image using a Gaussian filter.
    6integral(Mat src, Mat sum)It calculates the integral of an image.

    Example

    The following example demonstrates the use of Imgproc class to perform erosion and dilation on an image −

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    import org.opencv.highgui.Highgui;
    import org.opencv.imgproc.Imgproc;
    
    public class main {
       public static void main( String[] args ) {
       
    
      try{	
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         Mat source = Highgui.imread("digital_image_processing.jpg",  Highgui.CV_LOAD_IMAGE_COLOR);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         destination = source;
         int erosion_size = 5;
         int dilation_size = 5;
         
         Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new  Size(2*erosion_size + 1, 2*erosion_size+1));
         Imgproc.erode(source, destination, element);
         Highgui.imwrite("erosion.jpg", destination);
         source = Highgui.imread("digital_image_processing.jpg",  Highgui.CV_LOAD_IMAGE_COLOR);
         
         destination = source;
         
         Mat element1 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new  Size(2*dilation_size + 1, 2*dilation_size+1));
         Imgproc.dilate(source, destination, element1);
         Highgui.imwrite("dilation.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("error:" + e.getMessage());
      } 
    } }

    Output

    When you execute the given code, the following output is seen −

    Original Image

    Eroding and Dilating Tutorial

    On the above original image, some erosion and dilation operations have been performed which have been shown in the output below −

    Erosion

    Eroding and Dilating Tutorial

    Dilation

    Eroding and Dilating Tutorial