2017-09-29 251 views
0

圖像轉換爲灰度,但由於BufferedImage.TYPE_3BYTE_BGR而顯示在三個圖塊中。openCV將Mat轉換爲灰度圖像

.TYPE_BYTE_GRAY不起作用。

我該如何顯示一個灰度圖像?

public void matToBufferedImage(Mat matRGB){ 
    Mat mGray = new Mat(); 
    Imgproc.cvtColor(matRGB, mGray, Imgproc.COLOR_BGR2GRAY); 
    int width = mGray.width(), height = mGray.height(), channels = mGray.channels(); 
    byte[] source = new byte[width * height * channels]; 
    mGray.get(0, 0, source); 

    image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); 

    final byte[] target = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); 
    System.arraycopy(source, 0, target, 0, source.length); 
} 

回答

0

我對這種情況使用這兩種方法。

public static BufferedImage Mat2BufferedImage(Mat matrix) throws IOException { 
    MatOfByte mob=new MatOfByte(); 
    Imgcodecs.imencode(".jpg", matrix, mob); 
    return ImageIO.read(new ByteArrayInputStream(mob.toArray())); 
} 

public static Mat BufferedImage2Mat(BufferedImage image) throws IOException { 
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
    ImageIO.write(image, "jpg", byteArrayOutputStream); 
    byteArrayOutputStream.flush(); 
    return Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED); 
} 

所以,加入這兩種方法後,你會用他們像,

Imgproc.cvtColor(matRGB, mGray, Imgproc.COLOR_BGR2GRAY); 

image = Mat2BufferedImage(mGray); 
+0

這是視頻捕捉和識別。這些代碼是否也適用於這種情況,或者僅僅是靜止圖像? –

+0

視頻不過是圖像的集合。它會工作。你爲什麼不看到自己 – Ultraviolet