Java Dip Tutorial PDF
Java Dip Tutorial PDF
Audience
This reference has been prepared for the beginners to help them understand and
implement the basic to advance algorithms of digital image processing in java.
Prerequisites
Before proceeding with this tutorial, you need to have a basic knowledge of digital image
processing and Java programming language.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher. We strive to update the contents of our website and tutorials as timely
and as precisely as possible, however, the contents may contain inaccuracies or errors.
Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or
completeness of our website or its contents including this tutorial. If you discover any
errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com.
i
Java Digital Image Processing
Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Contents.................................................................................................................................................. ii
Constructors............................................................................................................................................ 2
Methods.................................................................................................................................................. 2
Example .................................................................................................................................................. 3
Output .................................................................................................................................................... 4
Downloading an Image............................................................................................................................ 6
Example .................................................................................................................................................. 7
Output .................................................................................................................................................... 8
Example ................................................................................................................................................ 10
Output .................................................................................................................................................. 13
Example ................................................................................................................................................ 16
Output .................................................................................................................................................. 18
ii
Java Digital Image Processing
Example ................................................................................................................................................ 20
Output .................................................................................................................................................. 21
Example ................................................................................................................................................ 24
Output .................................................................................................................................................. 25
Example ................................................................................................................................................ 27
Output .................................................................................................................................................. 28
Example ................................................................................................................................................ 31
Output .................................................................................................................................................. 32
Example ................................................................................................................................................ 35
Output .................................................................................................................................................. 36
Example ................................................................................................................................................ 40
Output .................................................................................................................................................. 41
Example ................................................................................................................................................ 45
Output .................................................................................................................................................. 46
Example ................................................................................................................................................ 50
Output .................................................................................................................................................. 51
Example ................................................................................................................................................ 55
iii
Java Digital Image Processing
Output .................................................................................................................................................. 57
Example ................................................................................................................................................ 59
Output .................................................................................................................................................. 60
Example ................................................................................................................................................ 63
Output .................................................................................................................................................. 64
Example ................................................................................................................................................ 68
Output .................................................................................................................................................. 69
Example ................................................................................................................................................ 73
Output .................................................................................................................................................. 74
Example ................................................................................................................................................ 76
Output .................................................................................................................................................. 77
Example ................................................................................................................................................ 81
Output .................................................................................................................................................. 82
Example ................................................................................................................................................ 85
Output .................................................................................................................................................. 87
Example ................................................................................................................................................ 91
iv
Java Digital Image Processing
Output .................................................................................................................................................. 93
Example ................................................................................................................................................ 97
Output .................................................................................................................................................. 99
Endrov................................................................................................................................................. 127
v
Java Digital Image Processing
vi
1. JAVA DIP — INTRODUCTION
Java Digital Image Processing
Digital Image Processing (DIP) deals with manipulation of digital images using a computer. It
is a subfield of signals and systems but focuses particularly on images. DIP focuses on
developing a computer system that is able to perform processing on an image. The input of
such system is a digital image. The system processes the image using efficient algorithms,
and gives an image as an output.
Java is a high level programming language that is widely used in the modern world. It can
support and handle digital image processing efficiently using various functions.
1
2. JAVA DIP — JAVA BUFFEREDIMAGE CLASS
Java Digital Image Processing
Java BufferedImage class is a subclass of Image class. It is used to handle and manipulate
the image data. A BufferedImage is made of ColorModel of image data. All BufferedImage
objects have an upper left corner coordinate of (0, 0).
Constructors
This class supports three types of constructors. The first constructor constructs a new
BufferedImage with a specified ColorModel and Raster.
The second constructor constructs a BufferedImage of one of the predefined image types.
The third constructor constructs a BufferedImage of one of the predefined image types:
TYPE_BYTE_BINARY or TYPE_BYTE_INDEXED.
Methods
Sr. No. Methods
1 copyData(WritableRaster outRaster)
2 getColorModel()
3 getData()
4 getData(Rectangle rect)
2
Java Digital Image Processing
5 getGraphics()
6 getHeight()
7 getMinX()
8 getMinY()
9 getRGB(int x, int y)
It returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and
default sRGB colorspace.
10 getType()
Example
The following example demonstrates the use of java BufferedImage class that draws some
text on the screen using Graphics Object:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
3
Java Digital Image Processing
g.drawImage(img, 20,20,this);
BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.getGraphics();
g.drawString("www.tutorialspoint.com", 20,20);
g.drawString("www.tutorialspoint.com", 20,40);
g.drawString("www.tutorialspoint.com", 20,60);
g.drawString("www.tutorialspoint.com", 20,80);
g.drawString("www.tutorialspoint.com", 20,100);
return bufferedImage;
frame.getContentPane().add(new Test());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
Output
When you execute the given code, the following output is seen:
4
Java Digital Image Processing
5
3. JAVA DIP — DOWNLOADING / UPLOADING IMAGES
Java Digital Image Processing
In this chapter we are going to see how you can download an image from internet, perform
some image processing techniques on the image, and then again upload the processed image
to a server.
Downloading an Image
In order to download an image from a website, we use Java class named URL, which can be
found under java.net package. Its syntax is given below:
Apart from the above method, there are other methods available in class URL as described
briefly:
6
Java Digital Image Processing
Example
The following example demonstrates the use of java URL class to download an image from
the internet:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
try{
String website =
"http://tutorialspoint.com/java_dip/images/"+fileName;
int length = 0;
outputStream.write(buffer, 0, length);
7
Java Digital Image Processing
inputStream.close();
outputStream.close();
}catch(Exception e){
Output
When you execute the given code, the following output is seen:
8
Java Digital Image Processing
Uploading an Image
Let us see how to upload an image to a webserver. We convert a BufferedImage to byte array
in order to send it to server.
We use Java class ByteArrayOutputStream, which can be found under java.io package. Its
syntax is given below:
Apart from the above method, there are other methods available in the
ByteArrayOutputStream class as described briefly:
This method resets the number of valid bytes of the byte array output stream to
zero, so that all the accumulated output in the stream is discarded.
9
Java Digital Image Processing
This method creates a newly allocated Byte array. Its size would be the current
size of the output stream and the contents of the buffer will be copied into it. It
returns the current contents of the output stream as a byte array.
Converts the buffer content into a string. Translation will be done according to the
default character encoding. It returns the String translated from the buffer's
content.
It writes len number of bytes starting from offset off to the stream.
It writes the entire content of this Stream to the specified stream argument.
Example
The following example demonstrates ByteArrayOutputStream to upload an image to the
server:
Client Code
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
10
Java Digital Image Processing
Socket soc;
soc=new Socket("localhost",4000);
try {
baos.flush();
baos.close();
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
dos.close();
out.close();
}catch (Exception e) {
soc.close();
11
Java Digital Image Processing
soc.close();
Server Code
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
socket=server.accept();
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
dis.readFully(data);
dis.close();
12
Java Digital Image Processing
in.close();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
Output
Client Side Output
When you execute the client code, the following output appears on client side:
After receiving the image, the server displays the image as shown below:
13
Java Digital Image Processing
14
4. JAVA DIP — IMAGE PIXELS
Java Digital Image Processing
An image contains a two dimensional array of pixels. It is actually the value of those pixels
that make up an image. Usually an image could be color or grayscale.
In Java, the BufferedImage class is used to handle images. You need to call getRGB() method
of the BufferedImage class to get the value of the pixel.
c.getRed();
c.getGreen();
c.getBlue();
Apart from these methods, there are other methods supported in the BufferedImage class.
They are described briefly:
1 copyData(WritableRaster outRaster)
15
Java Digital Image Processing
2 getColorModel()
3 getData()
4 getData(Rectangle rect)
5 getGraphics()
6 getHeight()
7 getMinX()
8 getMinY()
9 getRGB(int x, int y)
It returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and
default sRGB colorspace.
10 getType()
Example
The following example demonstrates the use of java BufferedImage class that displays pixels
of an image of size (10 x 10):
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
16
Java Digital Image Processing
import javax.swing.JFrame;
class Pixel {
BufferedImage image;
int width;
int height;
public Pixel() {
try {
image = ImageIO.read(input);
width = image.getWidth();
height = image.getHeight();
int count = 0;
count++;
} catch (Exception e) {}
17
Java Digital Image Processing
Output
When you execute the above example, it would print the pixels of the following image:
Original Image
Pixels Output
18
5. JAVA DIP — GRAYSCALE CONVERSION
Java Digital Image Processing
In order to convert a color image to Grayscale image, you need to read pixels or data of the
image using File and ImageIO objects, and store the image in BufferedImage object. Its
syntax is given below:
Further, get the pixel value using method getRGB() and perform GrayScale() method on it.
The method getRGB() takes row and column index as parameter.
Apart from these three methods, there are other methods available in the Color class as
described briefly:
1 brighter()
2 darker()
3 getAlpha()
It creates a Color object based on the specified values for the HSB color model.
19
Java Digital Image Processing
6 toString()
The last step is to add all these three values and set it again to the corresponding pixel value.
Its syntax is given below:
image.setRGB(j,i,newColor.getRGB());
Example
The following example demonstrates the use of Java BufferedImage class that converts an
image to Grayscale:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
BufferedImage image;
int width;
int height;
public GrayScale() {
try {
image = ImageIO.read(input);
width = image.getWidth();
height = image.getHeight();
20
Java Digital Image Processing
red+green+blue,red+green+blue);
image.setRGB(j,i,newColor.getRGB());
} catch (Exception e) {}
Output
When you execute the given example, it converts the image
digital_image_processing.jpg to its equivalent Grayscale image and write it on hard disk
with the name grayscale.jpg.
Original Image
21
Java Digital Image Processing
Grayscale Image
22
6. JAVA DIP — ENHANCING IMAGE CONTRAST
Java Digital Image Processing
In this chapter we learn how to enhance the contrast of an image using histogram
equalization.
We use the OpenCV function equalizeHist() method. It can be found under Imgproc
package. Its syntax is given below:
Imgproc.equalizeHist(source, destination);
1 Source
2 Destination
Apart from the equalizeHist() method, there are other methods provided by the Imgproc class.
They are described briefly:
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
23
Java Digital Image Processing
Example
The following example demonstrates the use of Imgproc class to enhance contrast of an
image:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
Mat(source.rows(),source.cols(),source.type());
Imgproc.equalizeHist(source, destination);
Highgui.imwrite("contrast.jpg", destination);
}catch (Exception e) {
24
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
25
7. ENHANCING IMAGE BRIGHTNESS
Java Digital Image Processing
In this chapter we enhance the brightness of an image by multiplying each pixel of the image
with an alpha value and adding another beta value to it.
We OpenCV function convertTo that does the above operation automatically. It can be found
under Mat package. Its syntax is given below:
int alpha = 2;
1 destination
It is destination image.
2 rtype
It is desired output matrix type or rather the depth, since the number of channels
are the same as the input. If rtype is negative, the output matrix has the same
type as the input.
3 alpha
4 beta
Apart from the convertTo() method, there are other methods provided by the Mat class. They
are described briefly:
2 copyTo(Mat m)
26
Java Digital Image Processing
3 diag()
4 dot(Mat m)
5 reshape(int cn)
Example
The following example demonstrates the use of Mat class to enhance brightness of an image:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_COLOR);
27
Java Digital Image Processing
source.type());
Highgui.imwrite("brightWithAlpha2Beta50.jpg", destination);
}catch (Exception e) {
Output
When you execute the given code, the following output is seen:
Original Image
28
Java Digital Image Processing
29
8. JAVA DIP — ENHANCING IMAGE SHARPNESS
Java Digital Image Processing
In this chapter we learn to increase the sharpness of an image using Gaussian filter.
First we use OpenCV function GaussianBlur. It can be found under Imgproc package. Its
syntax is given below:
1 source
It is source image.
2 destination
It is destination image.
3 Size
4 sigmaX
Further, we use OpenCV function addWeighted to apply image watermark to image. It can be
found under Core package. Its syntax is given below:
src1
1
It is first input array.
alpha
2
It is weight of the first array elements.
src2
3
It is second input array of the same size and channel number as src1.
30
Java Digital Image Processing
Beta
4
It is weight of the second array elements.
gamma
5
It is scalar added to each sum.
Dst
6 It is output array that has the same size and number of channels as the input
arrays.
Apart from the GaussianBlur() method, there are other methods provided by the Imgproc
class. They are described briefly:
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
Example
The following example demonstrates the use of Imgproc and Core class to apply sharpening
to an image:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
31
Java Digital Image Processing
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_COLOR);
Mat(source.rows(),source.cols(),source.type());
Highgui.imwrite("sharp.jpg", destination);
}catch (Exception e) {
Output
When you execute the given code, the following output is seen:
Original Image
32
Java Digital Image Processing
Sharpened Image
33
9. JAVA DIP — IMAGE COMPRESSION TECHNIQUES
Java Digital Image Processing
An image can easily be compressed and stored through Java. Compression of image involves
converting an image into jpg and storing it.
In order to compress an image, we read the image and convert into BufferedImage object.
From this ImageWriteParam object, you can set the compression by calling these two methods
which are setCompressionMode() and setCompressionQuality(). Their syntaxes are as given
below:
obj.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
obj.setCompressionQuality(0.05f);
1 MODE_DEFAULT
It is a constant value that may be passed into methods to enable that feature for
future writes.
2 MODE_DISABLED
It is a constant value that may be passed into methods to disable that feature for
future writes.
3 MODE_EXPLICIT
It is a constant value that may be passed into methods to enable that feature for
future writes.
Apart from the compressions methods, there are other methods provided by the
ImageWriteParam class. They are described briefly:
34
Java Digital Image Processing
1 canOffsetTiles()
It returns true if the writer can perform tiling with non-zero grid offsets while
writing.
2 getBitRate(float quality)
It returns a float indicating an estimate of the number of bits of output data for
each bit of input image data at the given quality level.
3 getLocale()
It returns the currently set Locale, or null if only a default Locale is supported.
4 isCompressionLossless()
5 unsetCompression()
6 unsetTiling()
Example
The following example demonstrates the use of ImageWriteParam class to compress an
image:
import java.io.*;
import java.util.*;
import javax.imageio.*;
import java.awt.image.*;
import javax.imageio.stream.ImageOutputStream;
class Compresssion {
35
Java Digital Image Processing
Iterator<ImageWriter>writers =
ImageIO.getImageWritersByFormatName("jpg");
writer.setOutput(ios);
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.05f);
os.close();
ios.close();
writer.dispose();
Output
When you execute the given code, it compresses the image digital_image_processing.jpg to
its equivalent compressed image and writes it on the hard disk with the name compress.jpg.
Original Image
36
Java Digital Image Processing
37
Java Digital Image Processing
38
10. JAVA DIP — ADDING IMAGEJavaBORDER
Digital Image Processing
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);
1 source
It is source image.
2 destination
It is destination image.
3 top
4 bottom
5 left
6 right
7 borderType
Apart from the copyMakeBorder() method, there are other methods provide by the Imgproc
class. They are described briefly:
39
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
40
Java Digital Image Processing
Highgui.CV_LOAD_IMAGE_COLOR);
Mat(source.rows(),source.cols(),source.type());
int borderType;
destination = source;
Highgui.imwrite("borderWrap.jpg", destination);
}catch (Exception e) {
Output
When you execute the given code, the following output is seen:
Original Image
41
Java Digital Image Processing
42
Java Digital Image Processing
43
11. JAVA DIP — IMAGE PYRAMIDS
Java Digital Image Processing
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.
We use OpenCV functions pyrUp and pyrDown. They can be found under Imgproc package. Its
syntax is given below:
Imgproc.pyrDown(source, destination,destinationSize);
1 source
2 destination
3 destinationSize
Apart from the pyrUp and pyrDown methods, there are other methods provided by the
Imgproc class. They are described briefly:
44
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_COLOR);
source.cols()*2,source.type());
destination1 = source;
45
Java Digital Image Processing
source.rows()*2));
Highgui.imwrite("pyrUp.jpg", destination1);
source = Highgui.imread("digital_image_processing.jpg",
Highgui.CV_LOAD_IMAGE_COLOR);
source.type());
destination = source;
source.rows()/2));
Highgui.imwrite("pyrDown.jpg", destination);
}catch (Exception e) {
Output
When you execute the given code, the following output is seen:
46
Java Digital Image Processing
Original Image
On the original image, pyrUp (UP Sampling) and pyrDown (Down Sampling) are performed.
The output after sampling is as shown below:
47
Java Digital Image Processing
PyrUP Image
pyrDown Image
48
12. JAVA DIP — BASIC THRESHOLDING
Java Digital Image Processing
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.
We use OpenCV function threshold. It can be found under Imgproc package. Its syntax is
given below:
1 source
It is source image.
2 destination
It is destination image.
3 thresh
It is threshold value.
4 maxval
5 type
Apart from these thresholding methods, there are other methods provided by the Imgproc
class. They are described briefly:
49
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
try{
50
Java Digital Image Processing
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_COLOR);
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) {
Output
When you execute the given code, the following output is seen:
Original Image
51
Java Digital Image Processing
On the above original image, some thresholding operation is performed which is shown in the
output below:
Thresh Binary
52
Java Digital Image Processing
Thresh Zero
53
13. JAVA DIP — IMAGE SHAPE CONVERSION
Java Digital Image Processing
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:
Flipping an Image
OpenCV allows three types of flip codes which are described below:
1 0
2 1
3 -1
We pass the appropriate flip code into method flip() in the Core class. Its syntax is given
below:
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:
54
Java Digital Image Processing
It draws a circle.
5 sumElems(Mat src)
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;
55
Java Digital Image Processing
try {
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
getDataBuffer()).getData();
mat.put(0, 0, data);
byte[mat1.rows()*mat1.cols()*(int)(mat1.elemSize())];
mat1.get(0, 0, data1);
image1.getRaster().setDataElements(0,0,mat1.cols(),mat1.rows(),data1);
} catch (Exception e) {
56
Java Digital Image Processing
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
Flipped Image
57
14. JAVA DIP — APPLYING GAUSSIAN FILTER
Java Digital Image Processing
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);
1 source
It is source image.
2 destination
It is destination image.
3 Size
4 SigmaX
Apart from the GaussianBlur method, there are other methods provided by the Imgproc class.
They are described briefly:
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
58
Java Digital Image Processing
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;
try {
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_COLOR);
Highgui.imwrite("Gaussian45.jpg", destination);
} catch (Exception e) {
59
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
When this original image is convolved with the Gaussian filter of size 11 and 45, the following
output is seen:
60
Java Digital Image Processing
61
15. JAVA DIP — APPLYING BOX FILTER
Java Digital Image Processing
We apply Box filter that blurs an image. A Box filter could be of dimensions 3x3, 5x5, 9x9 etc.
We use the OpenCV function filter2D() to apply Box filter to images. It can be found
under Imgproc package. Its syntax is given below:
1 src
It is source image.
2 dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is
the same as the source.
4 kernel
5 anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 Delta
7 BORDER_DEFAULT
Apart from the filter2D() method, there are other methods provided by the Imgproc class.
They are described briefly:
62
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
try {
63
Java Digital Image Processing
int kernelSize = 9;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
kernel.put(i,j, m);
Highgui.imwrite("output.jpg", destination);
} catch (Exception e) {
Output
When you execute the given code, the following output is seen:
Original Image
64
Java Digital Image Processing
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:
65
Java Digital Image Processing
66
16. JAVA DIP — ERODING ANDJava
DILATION
Digital Image Processing
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:
1 source
It is source image.
2 destination
It is destination image.
3 element
Apart from erode() and dilate() methods, there are other methods provided by the Imgproc
class. They are described briefly:
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
67
Java Digital Image Processing
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;
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_COLOR);
Mat(source.rows(),source.cols(),source.type());
destination = source;
int erosion_size = 5;
int dilation_size = 5;
68
Java Digital Image Processing
Highgui.imwrite("erosion.jpg", destination);
source = Highgui.imread("digital_image_processing.jpg",
Highgui.CV_LOAD_IMAGE_COLOR);
destination = source;
Highgui.imwrite("dilation.jpg", destination);
}catch (Exception e) {
Output
When you execute the given code, the following output is seen:
Original Image
69
Java Digital Image Processing
On the above original image, some erosion and dilation operations have been performed which
have been shown in the output below:
Erosion
Dilation
70
Java Digital Image Processing
71
17. JAVA DIP — APPLYING WATERMARK
Java Digital Image Processing
In this chapter we learn two ways of applying watermark on images. These ways are:
1 Source
It is source image.
2 Text
3 Point
4 fontFace
5 fontScale
6 color
It is text color.
Apart from the putText method, there are other methods provided by the Core class. They
are described briefly:
72
Java Digital Image Processing
1 normalize(Mat src, Mat dst, double alpha, double beta, int norm_type)
5 reduce(Mat src, Mat dst, int dim, int rtype, int dtype)
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;
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
73
Java Digital Image Processing
Highgui.CV_LOAD_IMAGE_COLOR);
source.type());
(source.rows()/2,source.cols()/2),
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:
74
Java Digital Image Processing
Original Image
75
Java Digital Image Processing
1 src1
2 alpha
3 src2
It is the second input array of the same size and channel number as src1.
4 beta
5 gamma
6 dst
It 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;
76
Java Digital Image Processing
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_COLOR);
Mat waterMark=Highgui.imread("watermark.png",
Highgui.CV_LOAD_IMAGE_COLOR);
waterMark.cols(),waterMark.rows());
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:
77
Java Digital Image Processing
Original Image
78
Java Digital Image Processing
Watermarked Image
79
18. JAVA DIP — UNDERSTANDING CONVOLUTION
Java Digital Image Processing
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:
1 src
It is source image.
2 dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is the
same as the source.
4 kernel
5 anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 delta
80
Java Digital Image Processing
7 BORDER_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;
try {
int kernelSize = 3;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
Mat(source.rows(),source.cols(),source.type());
put(0,0,0);
put(0,1,0);
put(0,2,0);
81
Java Digital Image Processing
put(1,0,0);
put(1,1,1);
put(1,2,0);
put(2,0,0);
put(2,1,0);
put(2,2,0);
};
Highgui.imwrite("original.jpg", destination);
} catch (Exception e) {
Output
In this example we convolve our image with the following filter (kernel). This filter results in
producing original image as it is:
0 0 0
0 1 0
0 0 0
82
Java Digital Image Processing
Original Image
Convolved Image
83
19. JAVA DIP — APPLYING PREWITT OPERATOR
Java Digital Image Processing
Prewitt operator is used for edge detection in an image. It detects two types of edges: vertical
edges and horizontal edges.
We use the OpenCV function filter2D() to apply Prewitt operator to images. It can be found
under Imgproc package. Its syntax is given below:
1 src
It is source image.
2 dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is
the same as the source.
4 kernel
5 anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 delta
7 BORDER_DEFAULT
Apart from the filter2D() method, there are other methods provide by the Imgproc class. They
are described briefly:
84
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
85
Java Digital Image Processing
try {
int kernelSize = 9;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
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);
};
Highgui.imwrite("output.jpg", destination);
} catch (Exception e) {
86
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
This original image is convolved with the Prewitt operator of vertical edges as given below:
Vertical direction
-1 0 1
-1 0 1
-1 0 1
87
Java Digital Image Processing
This original image has also been convolved with the Prewitt operator of horizontal edges,
which is given below:
Horizontal Direction
-1 -1 -1
0 0 0
1 1 1
88
Java Digital Image Processing
89
20. JAVA DIP — APPLYING SOBELJava
OPERATOR
Digital Image Processing
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 the OpenCV function filter2D() to apply Sobel operator to images. It can
be found under Imgproc package. Its syntax is given below:
1 src
It is source image.
2 dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is the
same as the source.
4 kernel
5 anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 Delta
7 BORDER_DEFAULT
Apart from the filter2D() method, there are other methods provide by the Imgproc class. They
are described briefly:
90
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
91
Java Digital Image Processing
try {
int kernelSize = 9;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
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);
};
Highgui.imwrite("output.jpg", destination);
} catch (Exception e) {
92
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
This original image is convolved with the Sobel operator of vertical edges, which is given
below:
Vertical Direction
-1 0 1
-2 0 2
-1 0 1
93
Java Digital Image Processing
This original image is convolved with the Sobel operator of horizontal edges, which is given
below:
Horizontal Direction
-1 -2 -1
0 0 0
1 2 1
94
Java Digital Image Processing
95
21. JAVA DIP — APPLYING KIRSCHJavaOPERATOR
Digital Image Processing
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 the OpenCV function filter2D() to apply Kirsch operator to images. It
can be found under Imgproc package. Its syntax is given below:
1 src
It is source image.
2 dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is
the same as the source.
4 Kernel
5 Anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 Delta
7 BORDER_DEFAULT
Apart from the filter2D() method, there are other methods provided by the Imgproc class.
They are described briefly:
96
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
97
Java Digital Image Processing
try {
int kernelSize = 9;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
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);
};
Highgui.imwrite("output.jpg", destination);
} catch (Exception e) {
98
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
This original image is convolved with the Kirsch operator of East edges as given below:
Kirsch East
-3 -3 -3
-3 0 -3
5 5 5
99
Java Digital Image Processing
This original image is convolved with the Kirsch operator of South West edges as given below:
5 0 -3
-3 -3 -3
100
Java Digital Image Processing
101
22. JAVA DIP — APPLYING ROBINSONOPERATOR
Java Digital Image Processing
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 the OpenCV function filter2D() to apply Robinson operator to images. It
can be found under Imgproc package. Its syntax is given below:
1 src
It is source image.
2 dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is the
same as the source.
4 kernel
5 anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 Delta
7 BORDER_DEFAULT
Apart from the filter2D() method, there are other methods provided by the Imgproc class.
They are described briefly:
102
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
103
Java Digital Image Processing
try {
int kernelSize = 9;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
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);
};
Highgui.imwrite("output.jpg", destination);
} catch (Exception e) {
104
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
This original image is convolved with the Robinson operator of North edges as given below:
-2 0 2
-1 0 1
105
Java Digital Image Processing
This original image has also been convolved with the Robinson operator of East edges as given
below:
0 0 0
1 2 1
106
Java Digital Image Processing
107
23. JAVA DIP — APPLYING LAPLACIAN OPERATOR
Java Digital Image Processing
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 the OpenCV function filter2D() to apply Laplacian operator to images. It can be found
under Imgproc package. Its syntax is given below:
1 Src
It is source image.
2 Dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is
the same as the source.
4 kernel
5 anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 delta
7 BORDER_DEFAULT
108
Java Digital Image Processing
Apart from the filter2D() method, there are other methods provided by the Imgproc class.
They are described briefly:
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
109
Java Digital Image Processing
try {
int kernelSize = 9;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
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);
};
Highgui.imwrite("output.jpg", destination);
} catch (Exception e) {
110
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
This original image is convolved with the Laplacian Negative operator as given below:
Laplacian Negative
0 -1 0
-1 4 -1
0 -1 0
111
Java Digital Image Processing
This original image is convolved with the Laplacian Positive operator as given below:
Laplacian Positive
0 1 0
1 -4 1
0 1 0
112
Java Digital Image Processing
113
24. JAVA DIP — APPLYING WEIGHTEDJava
AVERAGE FILTER
Digital Image Processing
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 the OpenCV function filter2D() to apply weighted average filter to images. It can be
found under Imgproc package. Its syntax is given below:
1 src
It is source image.
2 dst
It is destination image.
3 ddepth:
It is the depth of dst. A negative value (such as -1) indicates that the depth is the
same as the source.
4 kernel
5 anchor
It is the position of the anchor relative to its kernel. The location Point (-1, -1)
indicates the center by default.
6 Delta
7 BORDER_DEFAULT
Apart from the filter2D() method, there are other methods provide by the Imgproc class. They
are described briefly:
114
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
Example
The following example demonstrates the use of Imgproc class to apply weighted average 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;
115
Java Digital Image Processing
try {
int kernelSize = 9;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
m[k] = 10/18;
else{
m[k] = m[k]/(18);
kernel.put(i,j, m);
};
Highgui.imwrite("output.jpg", destination);
} catch (Exception e) {
116
Java Digital Image Processing
Output
When you execute the given code, the following output is seen:
Original Image
This original image is convolved with the weighted average filter as given below:
1 10 1
1 1 1
Convolved Image
117
Java Digital Image Processing
118
25. JAVA DIP — CREATING ZOOM EFFECT
Java Digital Image Processing
Zooming is the process of enlarging an image so that the details in the image become more
visible and prominent.
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.
1 INTER_NEAREST
It is nearest-neighbor interpolation.
2 INTER_LINEAR
3 INTER_AREA
It is resampling using pixel area relation. It may be a preferred method for image
decimation, as it gives more-free results.
4 INTER_CUBIC
5 INTER_LANCZOS4
Apart from the resize method, there are other methods provided by the Imgproc class. They
are described briefly:
119
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
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;
try {
int zoomingFactor = 2;
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
120
Java Digital Image Processing
Highgui.CV_LOAD_IMAGE_GRAYSCALE);
source.cols()* zoomingFactor,source.type());
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
121
Java Digital Image Processing
122
26. JAVA DIP — OPEN SOURCE Java
LIBRARIES
Digital Image Processing
In this chapter, we explore some of the free image processing libraries that are widely used
and can be easily integrated in the project. These libraries include:
ImageJ
Fiji
Commons Imaging
ImageMagick
Endrov
LeadTools
OpenCv
ImageJ
ImageJ is a public domain Java image processing program inspired by NIH Image for the
Macintosh. It can display, edit, analyze, process, save, and print 8-bit, 16-bit, and 32-bit
images.
1 Runs Everywhere
ImageJ is written in Java, which allows it to run on Linux, Mac OS X and Windows,
in both 32-bit and 64-bit modes.
2 Open Source
ImageJ and its Java source code are freely available and in the public domain.
3 Toolkit
4 Data Types
8-bit grayscale or indexed color, 16-bit unsigned integer, 32-bit floating-point, and
RGB color.
5 File Formats
Open and save GIF, JPEG, BMP, PNG, PGM, FITS, and ASCII. Open DICOM. Open
TIFFs, GIFs, JPEGs, DICOMs, and raw data using a URL.
123
Java Digital Image Processing
6 Selections
Create rectangular, elliptical, or irregular area selections. Create line and point
selections.
7 Image Enhancement
8 Color Processing
Split a 32-bit color image into RGB or HSV components. Merge 8-bit components
into a color image.
Fiji
Fiji is an image processing package. It can be described as a distribution of ImageJ and
ImageJ2 together with Java, Java3D, and a lot of plug-ins organized into a coherent menu
structure. Fiji compares to ImageJ as Ubuntu compares to Linux.
Apart from the ImageJ basic features, some of the advanced features of Fiji are described
below:
1 Registering 3D images
This involves Elastic Alignment and Montage, Feature Extraction, Image Stabilizer
etc.
2 Segmenting images
4 Scripting
Allow scripting with Macros, in JavaScript, JRuby, Jython, Clojure, and Beanshell.
5 Developing Plug-ins
Use the Script Editor to start developing plug-ins and then run the plug-ins.
6 ImageJ Tricks
124
Java Digital Image Processing
ImageJ is easy to use, but sometimes you wish for some function that is actually
implemented, yet you do not know how to trigger.
Commons Imaging
Apache Commons Imaging, previously known as Apache Commons Sanselan, is a library that
reads and writes a variety of image formats, including fast parsing of image information such
as size, color, space, ICC profile etc. and the metadata.
1 Java
Apache Commons Imaging is written in 100% pure Java. It executes on any JVM
and any platform, without modification.
2 Image Formats
It reads and writes a wide variety of image formats, and supports some variations
and encodings missed by all or most other libraries.
3 Metadata support
4 Network Friendly
It is network-friendly. Commons Imaging only reads the data it needs, and caches
what is read so that it is not too heavy on the network.
5 Easy to use
6 Transparent
7 Open Source
125
Java Digital Image Processing
8 Color Conversions
The ColorConversions class offers methods to convert between the following color
spaces: CIE-L*CH, CIE-L*ab, CIE-L*uv, CMY, CMYK, HSL, HSV, Hunter-Lab, RGB,
XYZ, and YXY.
ImageMagick
ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can
read and write images in more than 100 formats including DPX, EXR, GIF, JPEG, JPEG-2000,
PDF, PNG, Postscript, SVG, and TIFF. Use ImageMagick to resize, flip, mirror, rotate, distort,
shear, and transform images, adjust image colors, apply various special effects, or draw text,
lines, polygons, ellipses, and Bezier curve.
1 Format conversion
2 Transform
3 Transparency
4 Draw
5 Decorate
6 Special effects
7 Animation
8 Composite
126
Java Digital Image Processing
9 Morphology of shapes
Endrov
Endrov is a multi-purpose image analysis program. It is written independently and designed
to address many of the shortcomings of other free software and many commercial packages.
1 View data
It views data, in 2D and 3D. Designed to handle complex 4D data schemes and
unlimited number of channels, where each channel can have its own X, Y, and Z
resolution.
4 Lazy Evaluation
It is designed from the ground to handle large image sets. Endrov uses lazy
evaluation, a concept mostly available in research programming languages.
5 Scripting language
6 Java
Written in Java. Plug-in architecture allows easy extension with new Java plug-ins.
It can interact with Matlab.
7 Formats
It accesses almost all commercial and open file formats using Bio-formats.
127
Java Digital Image Processing
8 Microscopic Processing
It can control all your microscopes with one program and do on-the-fly image
analysis.
LEADTOOLS
LEADTOOLS provides over 200 image processing functions in several categories including
document cleanup, medical image enhancement, color conversion and correction, noise
reduction, edge detection, and more.
This powerful collection of functions can read scanned documents of artefacts and
imperfections such as punched holes, skewed angles, borders, dust speckles, and
more.
Enhance the image or highlight the details by shifting, selecting, subtracting, and
removing the background for better visuals.
3 Geometric Transformation
These functions can be used to clean, align, correct images, or apply artistic 3D
effects.
These functions can be used to enhance images, apply artistic effects, or aid in
diagnostic evaluation of medical images.
They can add image color space functionality to single and multi-threaded
applications including IIS and Windows WF hosted applications.
6 Color Correction
These functions are used to correct images with swapped color channels, balance
color intensities or perform various image analysis tasks.
7 Image Enhancement
128
Java Digital Image Processing
These functions are used to correct common errors in photography such as red-
eye and imbalanced colors as well as aid in diagnostic evaluation of medical
images.
8 Region of Interest
These functions are used to create and modify regions of interest in images to
perform image processing functions on specific portions of an image, save time in
bar-code, and OCR recognition or perform various image analysis tasks.
OpenCV
OpenCV is released under a BSD license and hence it is free for both academic and commercial
use. It has C++, C, Python, and Java interfaces and it supports Windows, Linux, Mac OS, iOS,
and Android. OpenCV was designed for computational efficiency and with a strong focus on
real-time applications. Written in optimized C/C++, the library can take advantage of multi-
core processing.
1 Smoothing Images
It can apply two very common morphology operators: Dilation and Erosion.
3 Morphology Transformations
4 Image Pyramids
129
Java Digital Image Processing
7 Remapping
8 Histogram Calculation
For simple purposes, OpenCV implements the function calcHist, which calculates
the histogram of a set of arrays (usually images or image planes). It can operate
with up to 32 dimensions.
130
27. JAVA DIP — INTRODUCTION TO OPENCV
Java Digital Image Processing
OpenCV is released under a BSD license and hence it is free for both academic and commercial
use. It has C++, C, Python, and Java interfaces, and it supports Windows, Linux, Mac OS,
iOS, and Android.
OpenCV was designed for computational efficiency and with a strong focus on real-time
applications. Written in optimized C/C++, the library can take advantage of multi-core
processing.
1 Smoothing Images
It can apply two very common morphology operators: Dilation and Erosion.
3 Morphology Transformations
4 Image Pyramids
7 Remapping
8 Histogram Calculation
131
Java Digital Image Processing
For simple purposes, OpenCV implements the function calcHist, which calculates
the histogram of a set of arrays (usually images or image planes). It can operate
with up to 32 dimensions.
Integrating OpenCV
The following steps explain how to integrate OpenCV into your applications.
Download OpenCV
You can download OpenCV from their official Website here.
Launch Eclipse.
Navigate under Java -> Build Path -> User Libraries and click New.
Now enter the name for your library. For example, OpenCV-2.4.6.
After that, select your new user library (i.e. OpenCV-2.4.6) and click on Add External JARs.
After adding the jar, extend the opencv-246.jar and select Native library location and press
Edit.
132
Java Digital Image Processing
Now your user library is created. Now you can reuse this configuration in any of the project.
On the Java Settings step, under Libraries tab, select Add Library... and select OpenCV-2.4.6,
then click Finish.
133
Java Digital Image Processing
134
28. JAVA DIP — GRAYSCALE CONVERSION OPENCV
Java Digital Image Processing
In order to convert a color image to Grayscale image using OpenCV, we read the image
into BufferedImage and convert it into Mat Object. Its syntax is given below:
Then you can transform the image from RGB to Grayscale format by using method cvtColor()
in the Imgproc class. Its syntax is given below:
The method cvtColor() takes three parameters which are the source image matrix, the
destination image matrix, and the color conversion type.
Apart from the cvtColor method, there are other methods provided by the Imgproc class.
They are described briefly:
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
135
Java Digital Image Processing
Example
The following example demonstrates the use of Imgproc class to convert an image to
Grayscale:
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;
try {
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
getDataBuffer()).getData();
CvType.CV_8UC3);
mat.put(0, 0, data);
136
Java Digital Image Processing
byte[mat1.rows()*mat1.cols()*(int)(mat1.elemSize())];
mat1.get(0, 0, data1);
,BufferedImage.TYPE_BYTE_GRAY);
image1.getRaster().setDataElements(0,0,mat1.cols(),mat1.rows(),data1);
} catch (Exception e) {
Output
When you execute the given example, it converts an image named
digital_image_processing.jpg to its equivalent Grayscale image and writes it on hard disk with
name grayscale.jpg.
137
Java Digital Image Processing
Original Image
Grayscale Image
138
29. JAVA DIP — COLORSPACE CONVERSION
Java Digital Image Processing
In order to change color space of one image to another using OpenCV, we read image
into BufferedImage and convert it into Mat Object. Its syntax is given below:
OpenCv allows many color conversion types, all of which can be found in the Imgproc class.
Some of the types are described briefly:
1 COLOR_RGB2BGR
2 COLOR_RGB2BGRA
3 COLOR_RGB2GRAY
4 COLOR_RGB2HLS
5 COLOR_RGB2HSV
6 COLOR_RGB2Luv
7 COLOR_RGB2YUV
8 COLOR_RGB2Lab
From any of the color conversion type, just pass the appropriate one into method cvtColor() in
the Imgproc class. Its syntax is given below:
The method cvtColor() takes three parameters which are the source image matrix, the
destination image matrix and the color conversion type.
Apart from the cvtColor() method, there are other methods provide by the Imgproc class.
They are described briefly:
139
Java Digital Image Processing
4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
Example
The following example demonstrates the use of Imgproc class to convert an image from one
color space to another.
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;
140
Java Digital Image Processing
try {
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
getDataBuffer()).getData();
mat.put(0, 0, data);
byte[mat1.rows()*mat1.cols()*(int)(mat1.elemSize())];
mat1.get(0, 0, data1);
image1.getRaster().setDataElements(0,0,mat1.cols(),mat1.rows(),data1);
} catch (Exception e) {
Output
When you execute the given example, it converts an image name
digital_image_processing.jpg to its equivalent HSV color space image and writes it on hard
disk with name hsv.jpg.
141
Java Digital Image Processing
142