Category: 01. Java Digital Image Processing

https://cdn3d.iconscout.com/3d/premium/thumb/image-processing-chip-3d-icon-download-in-png-blend-fbx-gltf-file-formats–processor-artificial-intelligence-pack-science-technology-icons-8306835.png?f=webp

  • 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
  • Applying Box Filter

    We apply Box filter that blurs an image. A Box filter could be of dimensions 3×3, 5×5, 9×9 etc.

    We use OpenCV function filter2D to apply Box 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.
    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 Box filter 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 = 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++) {
                  m[k] = m[k]/(kernelSize * kernelSize);
               }
               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 Box Filter Tutorial

    In this example we convolve our image with the following filter (kernel). This filter results in blurring an image as its size increases.

    This original image has been convolved with the box filter of size 5, which is given below −

    Box filter of size 5

    1/251/251/251/251/25
    1/251/251/251/251/25
    1/251/251/251/251/25
    1/251/251/251/251/25
    1/251/251/251/251/25

    Convolved Image (with Box Filter of Size 5)

    Applying Box Filter Tutorial

    Convolved Image (with Box Filter of Size 9)

    Applying Box Filter Tutorial
  • Applying Gaussian Filter

    In this chapter, we apply Gaussian filter to an image that blurs an image. We are going to use OpenCV function GaussianBlur to apply Gaussian filter to images. It can be found under Imgproc package. Its syntax is given below −

    Imgproc.GaussianBlur(source, destination,Size,SigmaX);
    

    The function arguments are described below −

    Sr.No.Argument & Description
    1sourceIt is source image.
    2destinationIt is destination image.
    3SizeIt is Gaussian kernel size.
    4SigmaXIt is Gaussian kernel standard deviation in X direction.

    Apart from the GaussianBlur 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 Gaussian filter to an image.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    import org.opencv.core.Size;
    
    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());
         Imgproc.GaussianBlur(source, destination,new Size(45,45), 0);
         Highgui.imwrite("Gaussian45.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 Gaussian Filter Tutorial

    When this original image is convolved with the Gaussian filter of size 11 and 45, the following output is seen.

    Gaussian filter of size 11

    Applying Gaussian Filter Tutorial

    Gaussian filter of size 45

    Applying Gaussian Filter Tutorial
  • Image Shape Conversion

    The shape of the image can easily be changed by using OpenCV. Image can either be flipped, scaled, or rotated in any of the four directions.

    In order to change the shape of the image, we read the image and convert into Mat object. Its syntax is given below −

    File input = new File("digital_image_processing.jpg");
    BufferedImage image = ImageIO.read(input);
    //convert Buffered Image to Mat.
    

    Flipping an Image

    OpenCV allows three types of flip codes which are described below −

    Sr.No.Flip Code & Description
    100 means, flipping around x axis.
    211 means, flipping around y axis.
    3-1-1 means, flipping around both axis.

    We pass the appropriate flip code into method flip() in the Core class. Its syntax is given below −

    Core.flip(source mat, destination mat1, flip_code);
    

    The method flip() takes three parameters − the source image matrix, the destination image matrix, and the flip code.

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

    Sr.No.Method & Description
    1add(Mat src1, Mat src2, Mat dst)It calculates the per-element sum of two arrays or an array and a scalar.
    2bitwise_and(Mat src1, Mat src2, Mat dst)It calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.
    3bitwise_not(Mat src, Mat dst)It inverts every bit of an array.
    4circle(Mat img, Point center, int radius, Scalar color)It draws a circle.
    5sumElems(Mat src)It blurs an image using a Gaussian filter.
    6subtract(Mat src1, Scalar src2, Mat dst, Mat mask)It calculates the per-element difference between two arrays or array and a scalar.

    Example

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

    import java.awt.image.BufferedImage;
    import java.awt.image.DataBufferByte;
    
    import java.io.File;
    import javax.imageio.ImageIO;
    
    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    import org.opencv.imgproc.Imgproc;
    
    public class Main {
       public static void main( String[] args ) {
       
    
      try {
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         File input = new File("digital_image_processing.jpg");
         BufferedImage image = ImageIO.read(input);	
         byte[] data = ((DataBufferByte) image.getRaster().  getDataBuffer()).getData();
         Mat mat = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC3);
         mat.put(0, 0, data);
         Mat mat1 = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC3);
         Core.flip(mat, mat1, -1);
         byte[] data1 = new byte[mat1.rows()*mat1.cols()*(int)(mat1.elemSize())];
         mat1.get(0, 0, data1);
         BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), 5);
         image1.getRaster().setDataElements(0,0,mat1.cols(),mat1.rows(),data1);
         File ouptut = new File("hsv.jpg");
         ImageIO.write(image1, "jpg", ouptut);
         
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
    } }

    Output

    When you run the above example, it would flip an image name digital_image_processing.jpg to its equivalent HSV color space image and write it on hard disk with name flip.jpg.

    Original Image

    Image Shape Conversion Tutorial

    Flipped Image

    Image Shape Conversion Tutorial
  • Basic Thresholding

    Thresholding enables to achieve image segmentation in the easiest way. Image segmentation means dividing the complete image into a set of pixels in such a way that the pixels in each set have some common characteristics. Image segmentation is highly useful in defining objects and their boundaries.

    In this chapter we perform some basic thresholding operations on images.

    We use OpenCV function threshold. It can be found under Imgproc package. Its syntax is given below −

    Imgproc.threshold(source, destination, thresh , maxval , type);
    

    The parameters are described below −

    Sr.No.Parameter & Description
    1sourceIt is source image.
    2destinationIt is destination image.
    3threshIt is threshold value.
    4maxvalIt is the maximum value to be used with the THRESH_BINARY and THRESH_BINARY_INV threshold types.
    5typeThe possible types are THRESH_BINARY, THRESH_BINARY_INV, THRESH_TRUNC, and THRESH_TOZERO.

    Apart from these thresholding 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 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 perform thresholding operations to 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;
         Imgproc.threshold(source,destination,127,255,Imgproc.THRESH_TOZERO);
         Highgui.imwrite("ThreshZero.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

    Basic Thresholding Tutorial

    On the above original image, some thresholding operations is performed which is shown in the output below −

    Thresh Binary

    Basic Thresholding Tutorial

    Thresh Binary Invert

    Basic Thresholding Tutorial

    Thresh Zero

    Basic Thresholding Tutorial
  • Image Pyramids

    Image pyramid is nothing but a method to display a multi-resolution image. The lowermost layer is a highest-resolution version of image and the topmost layer is a lowest-resolution version of the image. Image pyramids are used to handle image at different scales.

    In this chapter we perform some down sampling and up sampling on images.

    We use OpenCV functions pyrUp and pyrDown. They can be found under Imgproc package. Its syntax is given below −

    Imgproc.pyrUp(source, destination, destinationSize);
    Imgproc.pyrDown(source, destination,destinationSize);
    

    The parameters are described below −

    Sr.No.Parameter & Description
    1sourceIt is the source image.
    2destinationIt is the destination image.
    3destinationSizeIt is the size of the output image. By default, it is computed as Size((src.cols*2), (src.rows*2)).

    Apart from the pyrUp and pyrDown 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 up sampling and down sampling on an image.

    import org.opencv.core.Core;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    import org.opencv.core.Size;
    
    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 destination1 = new Mat(source.rows()*2, source.cols()*2,source.type());
         destination1 = source;
         
         Imgproc.pyrUp(source, destination1, new  Size(source.cols()*2   source.rows()*2));
         Highgui.imwrite("pyrUp.jpg", destination1);
         
         source = Highgui.imread("digital_image_processing.jpg", 
         Highgui.CV_LOAD_IMAGE_COLOR);
         
         Mat destination = new Mat(source.rows()/2,source.cols()/2, source.type());
         destination = source;
         Imgproc.pyrDown(source, destination, new Size(source.cols()/2,  source.rows()/2));
         Highgui.imwrite("pyrDown.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

    Image Pyramids Tutorial

    On the original image, pyrUp(UP Sampling) and pyrDown(Down Sampling) are performed. The output after sampling is as shown below −

    PyrUP Image

    Image Pyramids Tutorial

    pyrDown Image

    Image Pyramids Tutorial
  • Adding Border

    In this chapter we learn to add different types of borders to an image.

    We use OpenCV function copyMakeBorder. It can be found under Imgproc package. Its syntax is given below −

    Imgproc.copyMakeBorder(source,destination,top,bottom,left,right,borderType);
    

    The parameters are described below −

    Sr.No.Parameter & Description
    1sourceIt is source image.
    2destinationIt is destination image.
    3topIt is the length in pixels of the border at the top of the image.
    4bottomLength in pixels of the border at the bottom of the image.
    5leftIt is the length in pixels of the border at the left of the image.
    6rightIt is the length in pixels of the border at the right of the image.
    7borderTypeIt defines the type of border. The possible borders are BORDER_REPLICATE, BORDER_REFLECT, BORDER_WRAP, BORDER_CONSTANT etc.

    Apart from the copyMakeBorder() 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 add border to 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());
         
         int top, bottom, left, right;
         int borderType;
         /// Initialize arguments for the filter
         top = (int) (0.05*source.rows()); 
         bottom = (int) (0.05*source.rows());
         left = (int) (0.05*source.cols()); 
         right = (int) (0.05*source.cols());
         destination = source;
         Imgproc.copyMakeBorder(source, destination, top, bottom, left, right, Imgproc.BORDER_WRAP);
         Highgui.imwrite("borderWrap.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

    Adding Border Tutorial

    Isolated Border Image

    Adding Border Tutorial

    Wrapped Border Image

    Adding Border Tutorial

    Reflect Border Image

    Adding Border Tutorial