📜  Java DIP-OpenCV颜色空间转换

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


为了使用OpenCV将一幅图像的色彩空间更改为另一幅图像,我们将图像读入BufferedImage并将其转换为Mat对象。其语法如下-

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

OpenCv允许许多颜色转换类型,所有这些都可以在Imgproc类中找到。简要描述了一些类型-

Sr.No. Color Conversion Type
1 COLOR_RGB2BGR
2 COLOR_RGB2BGRA
3 COLOR_RGB2GRAY
4 COLOR_RGB2HLS
5 COLOR_RGB2HSV
6 COLOR_RGB2Luv
7 COLOR_RGB2YUV
8 COLOR_RGB2Lab

从任何一种颜色转换类型,只需将适当的一种传递到Imgproc类中的方法cvtColor()即可。其语法如下-

Imgproc.cvtColor(source mat, destination mat1, Color_Conversion_Code);

方法cvtColor()采用三个参数,分别是源图像矩阵,目标图像矩阵和颜色转换类型。

除了cvtColor()方法之外,Imgproc类还提供其他方法。他们简要描述-

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

下面的示例演示如何使用Imgproc类将图像从一种颜色空间转换为另一种颜色空间。

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);
         Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2HSV);

         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色彩空间图像,并将其写入名称为hsv.jpg的硬盘上。

原始影像(RGB)

OpenCV颜色空间转换教程

转换图像(HSV)

OpenCV颜色空间转换教程