我想在我的Java应用程序中流式传输摄像头,以获取一些图像处理功能。我正在使用随附的OpenCV和Java库文件。
我了解了如何捕获图像,但是又如何像视频一样连续捕获和显示帧。
请建议在下面的代码中进行修改,或以其他方式进行修改。
我正在使用Java Swing应用程序开发。
package openc;
import org.opencv.core.*;
public class openc {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
openc window = new openc();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public openc() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas canvas = new Canvas();
frame.getContentPane().add(canvas, BorderLayout.CENTER);
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture camera = new VideoCapture(0);
if(!camera.isOpened()){
System.out.println("Error");
}
else {
Mat iframe = new Mat();
while(true){
if (camera.read(iframe)){
System.out.println("Frame Obtained");
System.out.println("Captured Frame Width " +
iframe.width() + " Height " + iframe.height());
while(true){
Highgui.imwrite(canvas, iframe);
}
}
}
}
camera.release();
}
}
我了解了如何捕获图像,但是又如何像视频一样连续捕获和显示帧。
我从未使用过OpenCV API,所以我对该库一无所知。但是我认为您的问题是由无限循环引起的典型线程阻塞问题:
while(true){ // infinite loop
if (camera.read(iframe)) {
System.out.println("Frame Obtained");
System.out.println("Captured Frame Width " +
iframe.width() + " Height " + iframe.height());
while(true) { // another infinite loop
Highgui.imwrite(canvas, iframe);
}
}
}
您有两个无限循环正在阻塞事件调度线程,从而导致GUI无法响应。Swing是单线程的,您必须格外小心如何创建/更新Swing组件。
在这种特殊情况下,我认为您可以使用SwingWorker定期在后台线程中读取相机数据并更新Canvas
EDT中的对象。像这样:
SwingWorker<Void, Mat> worker = new SwingWorker<Void, Mat>() {
@Override
protected Void doInBackground() throws Exception {
while(!isCancelled()) {
if (camera.read(iframe)) {
publish(iframe);
}
Thread.sleep(500); // prudential time to avoid block the event queue
}
return null;
}
@Override
protected void process(List<Mat> chunks) {
Mat lastFrame = chuncks.get(chunks.size() - 1);
Highgui.imwrite(canvas, lastFrame);
}
};
worker.execute();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句