我正试图遵循OpenCV Javatorial,以学习图像处理方面的一些知识。
The tutorial suggest Java8, but I am using Java15 + JavaFX17. At the part of "Your First JavaFX Application with OpenCV", I encountered an issue, I can t convert BufferedImage to Image, as a result I can t show any frames from camera in my application.
我的法典如下:
package application;
import java.lang.System;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import org.opencv.core.Mat;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
public final class Utils
{
public static Image mat2Image(Mat frame)
{
try
{
System.err.println("Can you just simpily return something?");
BufferedImage test = matToBufferedImage(frame);
System.err.println(test);
Image test2 = SwingFXUtils.toFXImage(test, null);
System.err.println(test2);
return SwingFXUtils.toFXImage(matToBufferedImage(frame), null);
}
catch (Exception e)
{
System.err.println("Cannot convert the Mat obejct: " + e);
return null;
}
}
public static <T> void onFXThread(final ObjectProperty<T> property, final T value)
{
Platform.runLater(() -> {
property.set(value);
});
}
private static BufferedImage matToBufferedImage(Mat original)
{
// init
BufferedImage image = null;
int width = original.width(), height = original.height(), channels = original.channels();
byte[] sourcePixels = new byte[width * height * channels];
original.get(0, 0, sourcePixels);
if (original.channels() > 1)
{
image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
}
else
{
image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
}
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(sourcePixels, 0, targetPixels, 0, sourcePixels.length);
return image;
}
}
我试图利用言论和一些丑闻的信息来说明所发生的情况:
Can you just simpily return something?
BufferedImage@1b088e58: type = 10 ColorModel: #pixelBits = 8 numComponents = 1 color space = java.awt.color.ICC_ColorSpace@5333a296 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 640 height = 480 #numDataElements 1 dataOff[0] = 0
我的ToBufferedImage通常工作(也许我错了,但却没有工作),但SwadUtils.toFXImage失败。 我认为,我需要一些帮助,非常感谢你。