gpt4 book ai didi

java - openCV将Mat转换为灰度图像

转载 作者:太空宇宙 更新时间:2023-11-04 11:05:54 25 4
gpt4 key购买 nike

图像被覆盖为灰度,但由于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);

关于java - openCV将Mat转换为灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46492440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com