📜  Java DIP-图像形状转换

📅  最后修改于: 2020-12-14 05:39:18             🧑  作者: Mango


使用OpenCV可以轻松更改图像的形状。可以在四个方向中的任何一个方向上翻转,缩放或旋转图像。

为了改变图像的形状,我们读取图像并将其转换为Mat对象。其语法如下-

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

翻转图像

OpenCV允许以下三种类型的翻转代码-

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.

我们将适当的翻转代码传递到Core类的方法flip()中。其语法如下-

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

flip()方法采用三个参数-源图像矩阵,目标图像矩阵和翻转代码。

除了flip方法之外,Core类还提供了其他方法。他们简要描述-

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.

以下示例演示了如何使用Core类翻转图像-

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

输出

当您运行上述示例时,它会将图像名称digital_image_processing.jpg翻转到其等效的HSV色彩空间图像,并使用名称flip.jpg将其写入硬盘。

原始图片

图像形状转换教程

图像翻转

图像形状转换教程