图像被覆盖为灰度,但由于BufferedImage.TYPE_3BYTE_BGR,显示为三个图块。

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

最佳答案

在这种情况下,我使用这两种方法。

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

09-26 08:23