[英]openCV converting Mat to grayscale image
The image is coverted to grayscale but shows in three tiles because of the BufferedImage.TYPE_3BYTE_BGR
. 该图像被覆盖为灰度,但由于
BufferedImage.TYPE_3BYTE_BGR
而以三个图块显示。
.TYPE_BYTE_GRAY does not work. .TYPE_BYTE_GRAY不起作用。
how can I just display one grayscale image? 如何只显示一张灰度图像?
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);
}
I use these two methods for such cases. 在这种情况下,我使用这两种方法。
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);
}
So, after adding those two methods, you would use them like, 因此,在添加了这两种方法之后,您将像这样使用它们,
Imgproc.cvtColor(matRGB, mGray, Imgproc.COLOR_BGR2GRAY);
image = Mat2BufferedImage(mGray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.