我使用java-Swing实现了一个程序。这是一个基于网络摄像头的安全工具。在图像/位置改变时的活动模式下,它会发出蜂鸣声。
但问题是, - 它无法访问我的网络摄像头。我已经检查了我的网络摄像头驱动程序,它的运行完美。但是这个程序无法访问网络摄像头。 我已经添加了jmf.jar。
package jcam;
import com.sun.media.util.BufferToBufferedImage;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Vector;
import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.JFrame;
import jmapps.jmstudio.CaptureControlsDialog;
public class Jcam extends JFrame{
Player p;
Buffer buf;
BufferToImage btoi;
Image img, cimg;
boolean flag=false;
public Jcam(){
super("Jcam");
try {
Vector v = CaptureDeviceManager.getDeviceList(null);
CaptureDeviceInfo cam=null;
for(int i=0; i<v.size(); i++){
CaptureDeviceInfo dev = (CaptureDeviceInfo) v.elementAt(i);
if(dev.getName().startsWith("vfw"))
{
cam=dev;
break;
}
System.out.println(dev.getName());
}
if(cam==null)
{
System.out.println("no cam");
System.exit(0);
}
MediaLocator locator = cam.getLocator();
p = Manager.createRealizedPlayer(locator);
add(p.getVisualComponent());
p.start();
Thread thread = new Thread(){
public void run(){
while (true) {
FrameGrabbingControl fgc = (FrameGrabbingControl)
p.getControl("javax.media.control.FrameGrabbingControl");
buf= fgc.grabFrame();
btoi= new BufferToImage((VideoFormat) buf.getFormat());
cimg = btoi.createImage(buf);
if(img!=null){
if(com()>5999)
flag=true;
}
repaint();
img=cimg;
}
}
};
} catch (Exception e) {
System.out.println(e);
}
setSize(700,700);
setVisible(true);
}
public int com(){
BufferedImage image1= (BufferedImage) cimg;
BufferedImage image2= (BufferedImage) img;
int H= image1.getHeight();
int W= image1.getWidth();
int c=0;
for(int i=0; i<W;i++){
for(int j=0; j<H; j++){
int rgb = image1.getRGB(i, j);
int rgb2 = image2.getRGB(i, j);
int r1, r2, g1, g2, b1, b2;
r1= (rgb & 0x00ff0000) >> 16;
g1= (rgb & 0x0000ff00) >> 8;
b1= (rgb & 0x000000ff);
r2= (rgb2 & 0x00ff0000) >> 16;
g2= (rgb2 & 0x0000ff00) >> 8;
b2= (rgb2 & 0x000000ff);
int red = r1-r2;
int green = g1-g2;
int blue = b1-b2;
if(Math.abs(red)>30 || Math.abs(green)>30)
c++;
}
}
return c;
}
public void paint(Graphics g){
super.paint(g);
if(flag){
g.fillOval(300, 600, 50, 50);
flag=false;
}
}
public static void main(String[] args) {
// TODO code application logic here
new Jcam();
}
}
答案 0 :(得分:0)
首先:您应该重构代码并从图像捕获中分离Swing初始化。你的Jcam构造函数很糟糕。
第二:在这里你定义一个线程
Thread thread = new Thread(){
但它在哪里开始?
第三:你应该阅读Swing线程:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/