opencv对图片进行灰度化

来源:互联网 发布:龙少微信软件 编辑:程序博客网 时间:2024/04/29 09:34

opencv对图片进行灰度化:

 public class Opencv_test{          public static void main(String[] args) throws IOException{              System.loadLibrary(Core.NATIVE_LIBRARY_NAME);//必写,否则Mat会实例化失败             Opencv_test ot=new Opencv_test();            ot.toBlack_White();        } 

例图:
这里写图片描述

public void toBlack_White() throws IOException{            Mat grayMat = Highgui.imread("F:/workspace/opencv_test/src/com/yc/img/1.jpg");  //获取图片 转换为Mat            Imgproc.cvtColor(grayMat, grayMat, Imgproc.COLOR_RGB2GRAY);//灰度化处理            matToBufferedImage(grayMat);//将Mat类转换成BufferedImage在保存到本地        }

mat转BufferedImage

public void matToBufferedImage(Mat destmat) throws IOException{            FileOutputStream fos=new FileOutputStream(new File("F:/workspace/opencv_test/src/com/yc/img/2.jpg"));//获取输出流            Mat grayMat=destmat;             byte[] data1 = new byte[grayMat.rows() * grayMat.cols() * (int)(grayMat.elemSize())];             grayMat.get(0, 0, data1);             BufferedImage image1 = new BufferedImage(grayMat.cols(),                                     grayMat.rows(),BufferedImage.TYPE_BYTE_GRAY);             image1.getRaster().setDataElements(0, 0, grayMat.cols(), grayMat.rows(), data1);             Graphics graphics = image1.createGraphics();//获取画布             graphics.drawImage(image1, 0, 0, image1.getWidth(), image1.getHeight(), null);//生成图像              ImageIO.write(image1, "jpg", fos);//写入本地            fos.flush();            fos.close();        }

进行灰度化后的图片:

这里写图片描述

原创粉丝点击