Java DIP - OpenCV 灰度转换
为了使用 OpenCV 将彩色图像转换为灰度图像,我们将图像读入 BufferedImage 并将其转换为 Mat 对象。其语法如下 −
File input = new File("digital_image_processing.jpg"); BufferedImage image = ImageIO.read(input); //将缓冲图像转换为 Mat。
然后,您可以使用 Imgproc 类中的方法 cvtColor() 将图像从 RGB 转换为灰度格式。其语法如下 −
Imgproc.cvtColor(source mat, destination mat1, Imgproc.COLOR_RGB2GRAY);
方法 cvtColor() 需要三个参数,分别是源图像矩阵、目标图像矩阵和颜色转换类型。
除了 cvtColor 方法之外,Imgproc 类还提供了其他方法。它们列在下面 −
Sr.No. | 方法 &描述 |
---|---|
1 |
cvtColor(Mat src, Mat dst, int code, int dstCn) 它将图像从一个颜色空间转换为另一个颜色空间。 |
2 |
dilate(Mat src, Mat dst, Mat kernel) 它使用特定的结构元素来扩大图像。 |
3 |
equalizeHist(Mat src, Mat dst) 它均衡直方图灰度图像。 |
4 |
filter2D(Mat src, Mat dst, intdepth, Mat kernel, Point anchor, double delta) 它将图像与内核进行卷积。 |
5 |
GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX) 它使用高斯滤波器模糊图像。 |
6 |
integral(Mat src, Mat sum) 它计算图像的积分。 |
示例
以下示例演示了如何使用 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_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()); } } }
输出
执行给定示例时,它会将图像名称 digital_image_processing.jpg 转换为其等效的灰度图像,并将其写入硬盘上,名称为 grayscale.jpg。
原始图像

灰度图像
