相机使用
相机的使用依赖VideoCapture类与具体的硬件设备
VideoCapture类
new VideoCapture对象的时候,一个构造器为index的构造器决定了初始化时摄像头位置,0代表前置(面向用户),1代表后置。isOpened() 方法返回是否可用避免竞争资源。
Java代码(JavaFX Controller层)
public class Controller{
@FXML private Text fxText;
@FXML private ImageView imageView;
@FXML private TextArea textArea;
@FXML public void handleButtonEvent(ActionEvent actionEvent) throws IOException {
Node source = (Node) actionEvent.getSource();
Window theStage = source.getScene().getWindow();
runInSubThread(file.getPath());
}
private void runInSubThread(String filePath){
new Thread(new Runnable() {
@Override
public void run() {
try {
WritableImage writableImage = cameraCapture();
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage cameraCapture(){
WritableImage WritableImage = null;
// Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
// Instantiating the VideoCapture class (camera:: 0)
VideoCapture capture = new VideoCapture(0);
// Reading the next video frame from the camera
Mat matrix = new Mat();
capture.read(matrix);
// If camera is opened
if( capture.isOpened()) {
// If there is next video frame
if (capture.read(matrix)) {
// Creating BuffredImage from the matrix
BufferedImage image = new BufferedImage(matrix.width(),
matrix.height(), BufferedImage.TYPE_3BYTE_BGR);
WritableRaster raster = image.getRaster();
DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
byte[] data = dataBuffer.getData();
matrix.get(0, 0, data);
// Creating the Writable Image
WritableImage = SwingFXUtils.toFXImage(image, null);
}
}
return WritableImage;
}
}
相关图片