由于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);
}
答案 0 :(得分: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);