Java DIP – GrayScale Conversion ”; Previous Next 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 − File input = new File(“digital_image_processing.jpg”); BufferedImage image = ImageIO.read(input); Further, get the pixel value using method getRGB() and perform GrayScale() method on it. The method getRGB() takes row and column index as parameter. Color c = new Color(image.getRGB(j, i)); int red = (c.getRed() * 0.299); int green =(c.getGreen() * 0.587); int blue = (c.getBlue() *0.114); Apart from these three methods, there are other methods available in the Color class as described briefly − Sr.No. Method & Description 1 brighter() It creates a new Color that is a brighter version of this Color. 2 darker() It creates a new Color that is a darker version of this Color. 3 getAlpha() It returns the alpha component in the range 0-255. 4 getHSBColor(float h, float s, float b) It creates a Color object based on the specified values for the HSB color model. 5 HSBtoRGB(float hue, float saturation, float brightness) It converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model. 6 toString() It returns a string representation of this Color. The last step is to add all these three values and set it again to the corresponding pixel value. Its syntax is given below − int sum = red+green+blue; Color newColor = new Color(sum,sum,sum); 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; public class GrayScale { BufferedImage image; int width; int height; public GrayScale() { try { File input = new File(“digital_image_processing.jpg”); image = ImageIO.read(input); width = image.getWidth(); height = image.getHeight(); for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { Color c = new Color(image.getRGB(j, i)); int red = (int)(c.getRed() * 0.299); int green = (int)(c.getGreen() * 0.587); int blue = (int)(c.getBlue() *0.114); Color newColor = new Color(red+green+blue, red+green+blue,red+green+blue); image.setRGB(j,i,newColor.getRGB()); } } File ouptut = new File(“grayscale.jpg”); ImageIO.write(image, “jpg”, ouptut); } catch (Exception e) {} } static public void main(String args[]) throws Exception { GrayScale obj = new GrayScale(); } } 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 Grayscale Image Print Page Previous Next Advertisements ”;
Category: java Dip
DIP – Image Pixels
Java DIP – Image Pixels ”; Previous Next 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. Getting Pixel Value The pixel value can be received using the following syntax− Color c = new Color(image.getRGB(j, i)); Getting RGB Values The method getRGB() takes the row and column index as a parameter and returns the appropriate pixel. In case of color image, it returns three values which are (Red, Green, Blue). They can be get as follows− c.getRed(); c.getGreen(); c.getBlue(); Getting Width and Height of Image The height and width of the image can be get by calling the getWidth() and getHeight() methods of the BufferedImage class. Its syntax is given below− int width = image.getWidth(); int height = image.getHeight(); Apart from these methods, there are other methods supported in the BufferedImage class. They are described briefly− Sr.No. Method & Description 1 copyData(WritableRaster outRaster) It computes an arbitrary rectangular region of the BufferedImage and copies it into a specified WritableRaster. 2 getColorModel() It returns ColorModel of an image. 3 getData() It returns the image as one large tile. 4 getData(Rectangle rect) It computes and returns an arbitrary region of the BufferedImage. 5 getGraphics() This method returns a Graphics2D, but is here for backwards compatibility. 6 getHeight() It returns the height of the BufferedImage. 7 getMinX() It returns the minimum x coordinate of this BufferedImage. 8 getMinY() It returns the minimum y coordinate of this BufferedImage. 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() It returns the image type. Example The following example demonstrates the use of java BufferedImage class that displays pixels of an image of size (100 x 100)− import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.JFrame; class Pixel { BufferedImage image; int width; int height; public Pixel() { try { File input = new File(“blackandwhite.jpg”); image = ImageIO.read(input); width = image.getWidth(); height = image.getHeight(); int count = 0; for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { count++; Color c = new Color(image.getRGB(j, i)); System.out.println(“S.No: ” + count + ” Red: ” + c.getRed() +” Green: ” + c.getGreen() + ” Blue: ” + c.getBlue()); } } } catch (Exception e) {} } static public void main(String args[]) throws Exception { Pixel obj = new Pixel(); } } Output When you execute the above example, it would print the pixels of the following image − Original Image Pixels Output If you scroll down the ouput, the following pattern is seen− Print Page Previous Next Advertisements ”;
Downloading & Uploading Images ”; Previous Next 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 − String website = “http://tutorialspoint.com”; URL url = new URL(website); Apart from the above method, there are other methods available in class URL as described briefly − Sr.No. Method & Description 1 public String getPath() It returns the path of the URL. 2 public String getQuery() It returns the query part of the URL. 3 public String getAuthority() It returns the authority of the URL. 4 public int getPort() It returns the port of the URL. 5 public int getDefaultPort() It returns the default port for the protocol of the URL. 6 public String getProtocol() It returns the protocol of the URL. 7 public String getHost() It returns the host of the URL. 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; public class Download { public static void main(String[] args) throws Exception { try{ String fileName = “digital_image_processing.jpg”; String website = “http://tutorialspoint.com/java_dip/images/”+fileName; System.out.println(“Downloading File From: ” + website); URL url = new URL(website); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream(fileName); byte[] buffer = new byte[2048]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { System.out.println(“Buffer Read of length: ” + length); outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); } catch(Exception e) { System.out.println(“Exception: ” + e.getMessage()); } } } Output When you execute the given above, the following output is seen. It would download the following image from the server. 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 − ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, “jpg”, baos); In order to convert the image to byte array, we use toByteArray() method of ByteArrayOutputStream class. Its syntax is given below − byte[] bytes = baos.toByteArray(); Apart from the above method, there are other methods available in the ByteArrayOutputStream class as described briefly − Sr.No. Method & Description 1 public void reset() 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. 2 public byte[] toByteArray() 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. 3 public String toString() 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. 4 public void write(int w) It writes the specified array to the output stream. 5 public void write(byte []b, int of, int len) It writes len number of bytes starting from offset off to the stream. 6 public void writeTo(OutputStream outSt) 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; public class Client{ public static void main(String args[]) throws Exception{ Socket soc; BufferedImage img = null; soc=new Socket(“localhost”,4000); System.out.println(“Client is running. “); try { System.out.println(“Reading image from disk. “); img = ImageIO.read(new File(“digital_image_processing.jpg”)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(img, “jpg”, baos); baos.flush(); byte[] bytes = baos.toByteArray(); baos.close(); System.out.println(“Sending image to server. “); OutputStream out = soc.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeInt(bytes.length); dos.write(bytes, 0, bytes.length); System.out.println(“Image sent to server. “); dos.close(); out.close(); } catch (Exception e) { System.out.println(“Exception: ” + e.getMessage()); soc.close(); } soc.close(); } } Server Code import java.net.*; import java.io.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; class Server { public static void main(String args[]) throws Exception{ ServerSocket server=null; Socket socket; server = new ServerSocket(4000); System.out.println(“Server Waiting for image”); socket = server.accept(); System.out.println(“Client connected.”); InputStream in = socket.getInputStream(); DataInputStream dis = new DataInputStream(in); int len = dis.readInt(); System.out.println(“Image Size: ” + len/1024 + “KB”); byte[] data = new byte[len]; dis.readFully(data); dis.close(); in.close(); InputStream ian = new ByteArrayInputStream(data); BufferedImage bImage = ImageIO.read(ian); JFrame f = new JFrame(“Server”); ImageIcon icon = new ImageIcon(bImage); JLabel l = new JLabel(); 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 − Server Side Output When you execute the server code, the following ouptut appears on server side − After receiving the image, the server displays the image as shown below − Print Page Previous Next Advertisements ”;
Java DIP – Weighted Average Filter ”; Previous Next In weighted average filter, we gave more weight to the center value, due to which the contribution of center becomes more than the rest of the values. Due to weighted average filtering, we can control the blurring of image. We use OpenCV function filter2D to apply weighted average filter to images. It can be found under Imgproc package. Its syntax is given below − filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT ); The function arguments are described below − Sr.No. Argument & Description 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 It is the kernel to be scanned through the image. 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 It is a value to be added to each pixel during the convolution. By default it is 0. 7 BORDER_DEFAULT We let this value by default. Apart from the filter2D() method, there are other methods provide by the Imgproc class. They are described briefly − Sr.No. Method & Description 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 depth, 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 apply weighted average filter to an image of Graycale. import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class convolution { public static void main( String[] args ) { try { int kernelSize = 9; System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread(“grayscale.jpg”, Highgui.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(),source.cols(),source.type()); Mat kernel = Mat.ones(kernelSize,kernelSize, CvType.CV_32F) { for(int i=0; i<kernel.rows(); i++) { for(int j=0; j<kernel.cols(); j++) { double[] m = kernel.get(i, j); for(int k =0; k<m.length; k++) { if(i==1 && j==1) { m[k] = 10/18; } else{ m[k] = m[k]/(18); } } kernel.put(i,j, m); } } }; Imgproc.filter2D(source, destination, -1, kernel); Highgui.imwrite(“output.jpg”, destination); } catch (Exception e) { System.out.println(“Error: ” + e.getMessage()); } } } Output When you execute the given code, the following output is seen − Original Image This original image is convolved with the weighted average filter as given below − Weighted Average Filter 1 1 1 1 10 1 1 1 1 Convolved Image Print Page Previous Next Advertisements ”;
DIP – Quick Guide
Java DIP – Quick Guide ”; Previous Next Java DIP – Introduction Digital Image Processing (DIP) deals with manipulation of digital images using a digital computer. It is a sub field 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. Java BufferedImage Class 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. BufferedImage(ColorModel cm, WritableRaster raster, boolean isRasterPremultiplied, Hashtable<?,?> properties) The second constructor constructs a BufferedImage of one of the predefined image types. BufferedImage(int width, int height, int imageType) The third constructor constructs a BufferedImage of one of the predefined image types: TYPE_BYTE_BINARY or TYPE_BYTE_INDEXED. BufferedImage(int width, int height, int imageType, IndexColorModel cm) Sr.No Method & Description 1 copyData(WritableRaster outRaster) It computes an arbitrary rectangular region of the BufferedImage and copies it into a specified WritableRaster. 2 getColorModel() It returns object of class ColorModel of an image. 3 getData() It returns the image as one large tile. 4 getData(Rectangle rect) It computes and returns an arbitrary region of the BufferedImage. 5 getGraphics() This method returns a Graphics2D, retains backwards compatibility. 6 getHeight() It returns the height of the BufferedImage. 7 getMinX() It returns the minimum x coordinate of this BufferedImage. 8 getMinY() It returns the minimum y coordinate of this BufferedImage. 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() It returns the image type. Example The following example demonstrates the use of java BufferedImage class that draw 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; public class Test extends JPanel { public void paint(Graphics g) { Image img = createImageWithText(); g.drawImage(img, 20,20,this); } private Image createImageWithText() { BufferedImage bufferedImage = new 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; } public static void main(String[] args) { JFrame frame = new JFrame(); 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 − Downloading & Uploading Images 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 − String website = “http://tutorialspoint.com”; URL url = new URL(website); Apart from the above method, there are other methods available in class URL as described briefly − Sr.No. Method & Description 1 public String getPath() It returns the path of the URL. 2 public String getQuery() It returns the query part of the URL. 3 public String getAuthority() It returns the authority of the URL. 4 public int getPort() It returns the port of the URL. 5 public int getDefaultPort() It returns the default port for the protocol of the URL. 6 public String getProtocol() It returns the protocol of the URL. 7 public String getHost() It returns the host of the URL. 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; public class Download { public static void main(String[] args) throws Exception { try{ String fileName = “digital_image_processing.jpg”; String website = “http://tutorialspoint.com/java_dip/images/”+fileName; System.out.println(“Downloading File From: ” + website); URL url = new URL(website); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream(fileName); byte[] buffer = new byte[2048]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { System.out.println(“Buffer Read of length: ” + length); outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); } catch(Exception e) { System.out.println(“Exception: ” + e.getMessage()); } } } Output When you execute the given above, the following output is seen. It would download the following image from the server. 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 − ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, “jpg”, baos); In order to convert the image to byte array, we use toByteArray() method of ByteArrayOutputStream class. Its syntax is given below − byte[] bytes = baos.toByteArray(); Apart from the above method, there are other methods available in the ByteArrayOutputStream class as described briefly − Sr.No. Method & Description 1 public void reset() 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. 2 public byte[] toByteArray() 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. 3 public String toString() 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. 4 public void write(int w) It writes the specified array to the output stream. 5 public void write(byte
DIP – Laplacian Operator
Java DIP – Laplacian Operator ”; Previous Next Laplacian Operator is also a derivative operator which is used to find edges in an image. The major difference between Laplacian and other operators like Prewitt, Sobel, Robinson, and Kirsch is that these all are first order derivative masks but Laplacian is a second order derivative mask. We use OpenCV function filter2D to apply Laplacian operator to images. It can be found under Imgproc package. Its syntax is given below − filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT ); The function arguments are described below − Sr.No. Arguments 1 src It is source image. 2 dst It is destination image. 3 depth It is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source. 4 kernel It is the kernel to be scanned through the image. 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 It is a value to be added to each pixel during the convolution. By default it is 0. 7 BORDER_DEFAULT We let this value by default. Apart from the filter2D() method, there are other methods provided by the Imgproc class. They are described briefly − Sr.No. Method & Description 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 depth, 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 apply Laplacian operator to an image of Grayscale. import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class convolution { public static void main( String[] args ) { try { int kernelSize = 9; System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread(“grayscale.jpg”, Highgui.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(),source.cols(),source.type()); Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) { { put(0,0,0); put(0,1,-1) put(0,2,0); put(1,0-1); put(1,1,4); put(1,2,-1); put(2,0,0); put(2,1,-1); put(2,2,0); } }; Imgproc.filter2D(source, destination, -1, kernel); Highgui.imwrite(“output.jpg”, destination); } catch (Exception e) { System.out.println(“Error: ” + e.getMessage()); } } } Output When you execute the given code, the following output is seen − Original Image This original image is convolved with the Laplacian Negative operator as given below − Laplacian Negative 0 -1 0 -1 4 -1 0 -1 0 Convolved Image(Laplacian Negative) This original image is convolved with the Laplacian Positive operator as given below − Laplacian Positive 0 1 0 1 -4 1 0 1 0 Convolved Image (Laplacian Positive) Print Page Previous Next Advertisements ”;
DIP – Kirsch Operator
Java DIP – Kirsch Operator ”; Previous Next Kirsch compass masks are yet another type of derivative mask which are used for edge detection. This operator is also known as direction mask. In this operator we take one mask and rotate it in all the eight compass directions to get edges of the eight directions. We are going to use OpenCV function filter2D to apply Kirsch operator to images. It can be found under Imgproc package. Its syntax is given below − filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT ); The function arguments are described below − Sr.No. Argument 1 src It is source image. 2 dst It is destination image. 3 depth It is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source. 4 kernel It is the kernel to be scanned through the image. 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 It is a value to be added to each pixel during the convolution. By default it is 0. 7 BORDER_DEFAULT We let this value by default. Apart from the filter2D() method, there are other methods provided by the Imgproc class. They are described briefly − Sr.No. Method & Description 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 depth, 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 apply Kirsch operator to an image of Grayscale. import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class convolution { public static void main( String[] args ) { try { int kernelSize = 9; System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread(“grayscale.jpg”, Highgui.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(),source.cols(),source.type()); Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) { { put(0,0,-3); put(0,1,-3); put(0,2,-3); put(1,0-3); put(1,1,0); put(1,2,-3); put(2,0,5); put(2,1,5); put(2,2,5); } }; Imgproc.filter2D(source, destination, -1, kernel); Highgui.imwrite(“output.jpg”, destination); } catch (Exception e) { System.out.println(“Error: ” + e.getMessage()); } } } Output When you execute the given code, the following output is seen − Original Image This original image is convolved with the Kirsch operator of East edges, which as given below − Kirsch East -3 -3 -3 -3 0 -3 5 5 5 Convolved Image(Kirsch East) This original image is convolved with the Kirsch operator of South West edges, which as given below − Kirsch South West 5 5 -3 5 0 -3 -3 -3 -3 Convolved Image (Kirsch South West) Print Page Previous Next Advertisements ”;
Java DIP – Enhancing Image Brightness ”; Previous Next 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; int beta = 50; sourceImage.convertTo(destination, rtype , alpha, beta); The parameters are described below − Sr.No. Parameter & Description 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. Method & Description 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) Print Page Previous Next Advertisements ”;
Java DIP – OpenCV GrayScale Conversion ”; Previous Next 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 − File input = new File(“digital_image_processing.jpg”); BufferedImage image = ImageIO.read(input); //convert Buffered Image to Mat. Then you can transform the image from RGB to Grayscale format by using method cvtColor() in the Imgproc class. Its syntax is given below − Imgproc.cvtColor(source mat, destination mat1, Imgproc.COLOR_RGB2GRAY); 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 listed below − Sr.No. Method & Description 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 depth, 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 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; 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_8UC1); Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY); byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int)(mat1.elemSize())]; mat1.get(0, 0, data1); BufferedImage image1 = new BufferedImage(mat1.cols(),mat1.rows(), BufferedImage.TYPE_BYTE_GRAY); image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1); File ouptut = new File(“grayscale.jpg”); ImageIO.write(image1, “jpg”, ouptut); } catch (Exception e) { System.out.println(“Error: ” + e.getMessage()); } } } Output When you execute the given example, it converts an image name digital_image_processing.jpg to its equivalent Grayscale image and writes it on hard disk with name grayscale.jpg. Original Image Grayscale Image Print Page Previous Next Advertisements ”;
Java DIP – Image Shape Conversion ”; Previous Next The shape of the image can easily be changed by using OpenCV. Image can either be flipped, scaled, or rotated in any of the four directions. In order to change the shape of the image, we read the image and convert into Mat object. Its syntax is given below − File input = new File(“digital_image_processing.jpg”); BufferedImage image = ImageIO.read(input); //convert Buffered Image to Mat. Flipping an Image OpenCV allows three types of flip codes which are described below − Sr.No. Flip Code & Description 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. Method & Description 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 Print Page Previous Next Advertisements ”;