0% found this document useful (0 votes)
69 views39 pages

6 Enhancing Image

This document discusses techniques for image enhancement and compression in Java. It describes using OpenCV functions like equalizeHist(), convertTo(), and GaussianBlur() to enhance image contrast, brightness, and sharpness respectively. It also covers compressing an image by reading it into a BufferedImage, getting an ImageWriter, and setting the compression mode and quality using an ImageWriteParam object's methods.

Uploaded by

Vicky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views39 pages

6 Enhancing Image

This document discusses techniques for image enhancement and compression in Java. It describes using OpenCV functions like equalizeHist(), convertTo(), and GaussianBlur() to enhance image contrast, brightness, and sharpness respectively. It also covers compressing an image by reading it into a BufferedImage, getting an ImageWriter, and setting the compression mode and quality using an ImageWriteParam object's methods.

Uploaded by

Vicky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

6.

Enhancing Image

Java DIP - Enhancing Image Contrast


We use the OpenCV function equalizeHist() method. It can be found under Imgproc package.
Its syntax is given below:

Imgproc.equalizeHist(source, destination);

The parameters are described below:

Sr.No. Paramaeters

1 Source

It is 8-bit single channel source image.

2 Destination

It is the destination image.

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

Sr.No Method
.

1 cvtColor(Mat src, Mat dst, int code, int dstCn)

It converts an image from one color space to another.

2 dilate(Mat src, Mat dst, Mat kernel)

It dilates an image by using a specific structuring element.

3 equalizeHist(Mat src, Mat dst)

It equalizes the histogram of a grayscale image.

4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double
delta)

It convolves an image with the kernel.

5 GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)

It blurs an image using a Gaussian filter.

6 integral(Mat src, Mat sum)

It calculates the integral of an image.

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;

public class Main {

static int width;

static int height;

static double alpha = 2;

static double beta = 50;

public static void main( String[] args ) {

try {

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());

Imgproc.equalizeHist(source, destination);

Highgui.imwrite("contrast.jpg", destination);

}catch (Exception e) {

System.out.println("error: " + e.getMessage());

Output
Original Image
Enhanced Contrast Image

Java DIP - Enhancing Image Brightness


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;

int beta = 50;

sourceImage.convertTo(destination, rtype , alpha, beta);

The parameters are described below:

Sr.No Parameters
.

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 has. if rtype is negative, the output matrix will have the
same type as the input.

3 alpha

It is optional scale factor.

4 beta

It is optional delta added to the scaled values.

Apart from the convertTo method, there are other methods provided by the Mat class. They are
described briefly:

Sr.No Methods
.

1 adjustROI(int dtop, int dbottom, int dleft, int dright)

It adjusts a submatrix size and position within the parent matrix.

2 copyTo(Mat m)

It copies the matrix to another one.

3 diag()

It extracts a diagonal from a matrix, or creates a diagonal matrix.

4 dot(Mat m)

It computes a dot-product of two vectors.

5 reshape(int cn)

It changes the shape and/or the number of channels of a 2D matrix without


copying the data.

6 submat(Range rowRange, Range colRange)

It extracts a rectangular sub matrix.

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;

public class Main {

static int width;

static int height;

static double alpha = 2;

static double beta = 50;

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());

source.convertTo(destination, -1, alpha, beta);


Highgui.imwrite("brightWithAlpha2Beta50.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
Enhanced Bright Image (Alpha=1 & Beta=50)
Enhanced Bright Image (Alpha=2 & Beta=50)

Java DIP - Enhancing Image Sharpness


we learn to increase the sharpness of an image using Gaussian filter.

First we use OpenCV function GaussianBlur. It can be found under Imgprocpackage. Its


syntax is given below:

Imgproc.GaussianBlur(source, destination, new Size(0,0), sigmaX);

The parameters are described briefly:

Sr.No. Parameters

1 source

It is source image.

2 destination
It is destination image.

3 Size

It is Gaussian kernel size.

4 sigmaX

It is Gaussian kernel standard deviation in X direction.

Further, we 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, beta, gamma, OutputArray dst);

The parameters of this function are described below:


Sr.No
Parameters
.

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.

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:

Sr.No Methods
.

1 cvtColor(Mat src, Mat dst, int code, int dstCn)

It converts an image from one color space to another.

2 dilate(Mat src, Mat dst, Mat kernel)

It dilates an image by using a specific structuring element.

3 equalizeHist(Mat src, Mat dst)

It equalizes the histogram of a grayscale image.

4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double
delta)

It convolves an image with the kernel.

5 GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)

It blurs an image using a Gaussian filter.

6 integral(Mat src, Mat sum)

It calculates the integral of an image.

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;
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(0,0), 10);

Core.addWeighted(source, 1.5, destination, -0.5, 0, destination);

Highgui.imwrite("sharp.jpg", destination);

}catch (Exception e) {

Output
When you execute the given code, the following output is seen:
Original Image

Sharpened Image
Java DIP - Image Compression Technique
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.

Further, we get an ImageWriter from getImageWritersByFormatName()method found in the


ImageIO class. From this ImageWriter, create an ImageWriteParam object. Its syntax is given
below:

Iterator<ImageWriter> list = ImageIO.getImageWritersByFormatName("jpg");

ImageWriteParam obj = writer_From_List.getDefaultWriteParam();

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);

The setCompressionMode() method takes Mode_EXPLICIT as the parameter. Some of the


other MODES are described briefly:

Sr.No Modes
.

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:

Sr.No Methods
.

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()

It returns true if the current compression type provides lossless compression.

5 unsetCompression()

It removes any previous compression type and quality settings.

6 unsetTiling()

It removes any previous tile grid parameters specified by calls to setTiling.

Example
The following example demonstrates the use of ImageWriteParam class to compress an image:
import java.io.*;

import java.util.*;

import java.awt.image.*;

import javax.imageio.*;

import javax.imageio.stream.ImageOutputStream;

class Compresssion {

public static void main(String[] args) throws IOException {

File input = new File("digital_image_processing.jpg");

BufferedImage image = ImageIO.read(input);

File compressedImageFile = new File("compress.jpg");

OutputStream os =new FileOutputStream(compressedImageFile);

Iterator<ImageWriter>writers = ImageIO.getImageWritersByFormatName("jpg");

ImageWriter writer = (ImageWriter) writers.next();

ImageOutputStream ios = ImageIO.createImageOutputStream(os);

writer.setOutput(ios);

ImageWriteParam param = writer.getDefaultWriteParam();

param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.05f);

writer.write(null, new IIOImage(image, null, null), param);

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
Compressed Image - Quality Factor: 0.05

Compressed Image - Quality Factor: 0.5

Java DIP - Adding Border


We use OpenCV function copyMakeBorder. It can be found under Imgprocpackage. Its
syntax is given below:

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

The parameters are described below:

Sr.No Parameters
.

1 source

It is source image.

2 destination

It is destination image.

3 top

It is the length in pixels of the border at the top of the image.

4 bottom

Length in pixels of the border at the bottom of the image.

5 left

It is the length in pixels of the border at the left of the image.

6 right

It is the length in pixels of the border at the right of the image.

7 borderType

It 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 Methods
.

1 cvtColor(Mat src, Mat dst, int code, int dstCn)

It converts an image from one color space to another.

2 dilate(Mat src, Mat dst, Mat kernel)

It dilates an image by using a specific structuring element.

3 equalizeHist(Mat src, Mat dst)

It equalizes the histogram of a grayscale image.

4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double
delta)

It convolves an image with the kernel.

5 GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)

It blurs an image using a Gaussian filter.

6 integral(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
Isolated Border Image

Wrapped Border Image


Reflect Border Image

Java DIP - 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 Parameters
.

1 source
It is the source image.

2 destination

It is the destination image.

3 destinationSize

It 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 Methods
.

1 cvtColor(Mat src, Mat dst, int code, int dstCn)

It converts an image from one color space to another.

2 dilate(Mat src, Mat dst, Mat kernel)

It dilates an image by using a specific structuring element.

3 equalizeHist(Mat src, Mat dst)

It equalizes the histogram of a grayscale image.

4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double
delta)

It convolves an image with the kernel.

5 GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)

It blurs an image using a Gaussian filter.


6 integral(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

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

pyrDown Image

Java DIP - 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 Imgprocpackage. Its syntax is


given below:

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

The parameters are described below:

Sr.No Parameters
.

1 source

It is source image.

2 destination

It is destination image.

3 thresh

It is threshold value.

4 maxval

It is the maximum value to be used with the THRESH_BINARY and


THRESH_BINARY_INV threshold types.

5 type

The 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 Methods
.

1 cvtColor(Mat src, Mat dst, int code, int dstCn)

It converts an image from one color space to another.

2 dilate(Mat src, Mat dst, Mat kernel)

It dilates an image by using a specific structuring element.

3 equalizeHist(Mat src, Mat dst)

It equalizes the histogram of a grayscale image.

4 filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double
delta)

It convolves an image with the kernel.

5 GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)

It blurs an image using a Gaussian filter.

6 integral(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

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

Thresh Binary
Thresh Binary Invert

Thresh Zero

Java DIP - 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

1 0

0 means, flipping around x axis.

2 1

1 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 Methods
.

1 add(Mat src1, Mat src2, Mat dst)

It calculates the per-element sum of two arrays or an array and a scalar.

2 bitwise_and(Mat src1, Mat src2, Mat dst)

It calculates the per-element bit-wise conjunction of two arrays or an array and a


scalar.

3 bitwise_not(Mat src, Mat dst)

It inverts every bit of an array.

4 circle(Mat img, Point center, int radius, Scalar color)

It draws a circle.

5 sumElems(Mat src)

It blurs an image using a Gaussian filter.

6 subtract(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
FLIPPED IMAGE

You might also like