Image Processing in Java – Mirroring Image, Face Detection, Watermarking

Image processing is a complex part of computer graphic systems. The role of Java in it has created a huge milestone in achieving desired results. Image processing in java is the method of undergoing certain operations on an image and getting an enhanced image from a given image.

Due to its advancement, not everyone can perform image processing easily. You must learn to perform the methods in the right way. This article will lend you a helping hand in understanding the basics of it. Let’s start!!!

Image Processing in Java

1. Read and Write Image in Java

There are various classes to play or complete the processing of Java Image:

  • To read and write a picture document, we need to import the File class [import java.io.File;]. This class records the catalog way names when all is said and done.
  • To deal with the errors, we utilize the IOException class [import java.io.IOException;].
  • For holding the picture, we can imply the BufferedImage protest. For that, we utilize BufferedImage class [import java.awt.image.BufferedImage;]. It utilizes to store a picture in RAM.
  • To play out the picture read compose activity we would import the ImageIO class [import javax.imageio.ImageIO;]. This class contains static strategies to compose a picture.

Sample program to implement Java image processing:

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class NewImage
{
public static void main(String args[])throws IOException
{
int width = 920;  
 //image width
int height = 570;  
//image height
BufferedImage image = null;
try
{
File input_file = new File("G:\\Input.jpg"); //image file path
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
image = ImageIO.read(input_file);
System.out.println("Reading complete.");
}catch(IOException e)
{
System.out.println("Error: "+e);
}
try
{           
File output_file = new File("G:\\Output.jpg");
ImageIO.write(image, "jpg", output_file);
System.out.println("Writing complete.");
}
catch(IOException e)
{
System.out.println("Error: "+e);
}
}
}

Output:

Reading complete

Writing complete

2. Getting and Setting of Pixel Value in Java:

This is a vital part of Java Image Processing as the pixels are the smallest unit of a picture. It comprises four parts Alpha, Red, Green, and Blue and in short, is (ARGB).

The estimation of a notable number of segments that lie in the vicinity of 0 and 255 is comprehensive. When the part is missing, it is denoted as 0. And when the segment is completely present, it is denoted as 255.

Note:

Since 2^8 = 256 and the estimation of the pixel parts is present in the vicinity of 0 of 255. So, we need 8-bits to store the equalities. In the same way, it adds up to a number of bits required to store the ARGB esteems is 8*4=32 bits or 4 bytes. As the request implies,

Alpha procures the furthest left 8 bits, Blue holds the furthest right 8 bits.

Bit position in Java

  • The blue segment is 7-0
  • Green segment being 15-8
  • The red segment is 23-16
  • The alpha segment is 31-24

Program to work with Pixel value in java:

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class GetSetPixels
{
public static void main(String args[])throws IOException
{
BufferedImage img = null;
File f = null;
//read image
try
{
f = new File("G:\\Input.jpg");
img = ImageIO.read(f);
}
catch(IOException e)
{
System.out.println(e);
}
int width = img.getWidth();
int height = img.getHeight();
int p = img.getRGB(0,0);
int a = (p>>24) & 0xff;
int r = (p>>16) & 0xff;
int g = (p>>8) & 0xff;
int a = p & 0xff;
a = 255;
r = 100;
g = 150;
b = 200;
p = (a<<24) | (r<<16) | (g<<8) | b;
img.setRGB(0, 0, p);
try
{
f = new File("G:\\Output.jpg");
ImageIO.write(img, "jpg", f);
}
catch(IOException e)
{
System.out.println(e);
}}
}

3. Creating a Random Pixel Java Image:

Algorithm to create random pixel image:

1. Firstly, set the dimension of the desired image.

2. Secondly, we must create BufferedImage object to hold that image.

3. Now, we must generate random numbers of red, green, and alfa components.

4. We need to set the randomly generate ARGB.

5. Repeat the 3rd and 4th steps for each pixel.

Sample program to implement the above given algorithm:

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class NewImage
{
public static void main(String args[])throws IOException
{
int width = 640, height = 320;
BufferedImage img = null;
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
File f = null;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int a = (int)(Math.random()*256); 
int r = (int)(Math.random()*256); 
int g = (int)(Math.random()*256); 
int b = (int)(Math.random()*256); 
int p = (a<<24) | (r<<16) | (g<<8) | b; 
img.setRGB(x, y, p);
}
}
try
{
f = new File("G:\\Output.jpg");
ImageIO.write(img, "jpg", f);
}
catch(IOException e)
{
System.out.println("Error: " + e);
}}
}

4. Creating Mirror Image in Java:

The basic logic behind this process is to attain the source pixel esteems from left to right and set the same in the outcome picture from appropriate to left.

Algorithm to create a mirror image in Java:

1. Read the source picture in a BufferedImage to check the given picture.

2. Get the measurements of the picture.

3. Make another BufferedImage question of the same measurement to hold the identical representation.

4. Get the ARGB(Alpha, Red, Green, and Blue) values from the course picture.

5. Rehash the means 4 and 5 for every pixel of the picture.

Sample program to implement the Mirror image algorithm:

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class FirstCodeMirrorImage
{
public static void main(String args[])throws IOException{
BufferedImage simg = null;
File f = null;
try{
f = new File("G:\\Input.jpg");
simg = ImageIO.read(f);
}
catch(IOException e){
System.out.println("Error: " + e);
}
int width = simg.getWidth();
int height = simg.getHeight();
BufferedImage mimg = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++)
{
for (int lx = 0, rx = width - 1; lx < width; lx++, rx--){
int p = simg.getRGB(lx, y);
mimg.setRGB(rx, y, p);
}}
try
{
f = new File("G:\\Output.jpg");
ImageIO.write(mimg, "jpg", f);
}catch(IOException e)
{
System.out.println("Error: " + e);
}}
}

5. Face detection in Java:

  • Basically, in Java Image Processing, the BufferedImage class of Java was used to create pictures. There are many restrictions to the activities that can perform. We can adjust the R, G, B values of the picture and create one.
  • In case of complex picture handling, that is, confront/ protest recognition OpenCV library is used.
  • To begin with, we must set up OpenCV for Java using obscure.

Below are the strategies for face detection in Java:

a. CascadeClassifier(): This class is used to stack the prepared fell arrangement of faces that will distinguish the look for any info picture.

b. imread() / Imcodecs.imwrite(): We can use these techniques to peruse and compose pictures as Mat items. These items are usually rendered by the OpenCV.

c. rectangle(): We can use this method to create a rectangle box by sketching the appearances in a distinguished manner. It requires four contentions: input_image, top_left_point_, bottom_right_point, color_of_border.

Sample program to implement face detection in Java:

package ocv;
import org.opencv.core.Core;      
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
public class FirstCodeFaceDetector
{
public static void main(String[] args)
{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
CascadeClassifier faceDetector = new CascadeClassifier();
faceDetector.load("haarcascade_frontalface_alt.xml");
Mat image = Imgcodecs.imread("E:\\input.jpg");
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
for (Rect rect : faceDetections.toArray())
{
Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
}
String filename = "Ouput.jpg";
Imgcodecs.imwrite("E:\\"+filename, image);
}
}

6. Watermarking in images in Java:

To create content and apply it to a picture, we can use the java.awt.Graphics.Bundle.Textual style and shade of content. This is connected to the java.awl.Color and java.awt.Font classes.

The techniques that take place in the code are:

a. getGraphics(): It is present in the BufferedImage class. It helps us restore a 2D Graphics protest from the picture record.

b. drawImage(Image img, int x, int y, ImageObserver onlooker): The areas x and y denote the situation for the upper left of the picture. The eyewitness parameter advises the use of updates on a picture that is stacked concurrently.

c. setFont(Font f): This technique is present in the Font class of awt bundle and the constructor considers (FONT_TYPE, FONT_STYLE, FONT_SIZE) as contentions.

d. setColor(Color c): This technique is available in the Color class of awt bundle. And the constructor takes (R, G, B, An) as contentions.

e. drawString(Stringstr, int x, int y): this technique is available in the Graphics class. It takes the string content and the area coordinates as x and y as contentions.

Sample program to implement watermarking in Java:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class FirstCodeWaterMark
{
public static void main(String[] args)
{
BufferedImage img = null;
File f = null;
try{
f = new File("input.png");
img = ImageIO.read(f);
}
catch(IOException e){
System.out.println(e);
}
BufferedImage temp = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics graphics = temp.getGraphics();
graphics.drawImage(img, 0, 0, null);
graphics.setFont(new Font("Arial", Font.PLAIN, 80));
graphics.setColor(new Color(255, 0, 0, 40));=
String watermark = "WaterMark generated";
graphics.drawString(watermark, img.getWidth()/5, img.getHeight()/3); graphics.dispose();
f = new File("output.png");
try{
ImageIO.write(temp, "png", f);
}
catch (IOException e){
System.out.println(e);
}
}
}

7. Changing orientation of Image in Java:

We must use OpenCV to change the introduction of any info picture, by utilizing the CORE.flip() strategy for the OpenCV library.

The basic idea is that an info orientation of the picture will change over to a tangle protest. And later it will change to another tangle protest that will make the first tangle protest estimation as if it is put after introduction alternation.

a. getRaster(): This strategy restores a writeable raster which is further utilized to get the crude information from the input picture.

b. put(int push, int section, byte[] information) /get(int push, int segment, byte[] information): It is useful to peruse/compose the crude information into a tangle question.

c. flip(mat mat1, tangle mat2, int flip_value): mat1 and mat2 compare to info and yield tangle objects, and the flip_value chooses the introduction type. flip_value can be either 0 (flipping along x-hub), 1(flipping along y-hub), -1(flipping along both the hub).

Sample program to implement changing orientation of image in Java:

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
public class FirstCodeOrientingImage
{
public static void main( String[] args ) throws IOException
{  
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
File input = new File("E:\\test.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 newMat = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC3);
Core.flip(mat, newMat, -1);  //flipping the image about both axis  
byte[] newData = new byte[newMat.rows()*newMat.cols()*(int)(newMat.elemSize())];
newMat.get(0, 0, newData);
BufferedImage image1 = new BufferedImage(newMat.cols(), newMat.rows(), 5);
image1.getRaster().setDataElements(0,0,newMat.cols(),newMat.rows(),newData);
File ouptut = new File("E:\\result.jpg");
ImageIO.write(image1, "jpg", ouptut);
}
}

Conclusion

In this article, you have learned various image processing parts. Apart from these topics, it also includes the conversion of colored images to greyscale, negative, Red Green Blue, Sepia images too. These topics are in Image Processing Part 2. SO do not forget to check the other articles also.

Leave a Reply

Your email address will not be published. Required fields are marked *