JWorld@TW the best professional Java site in Taiwan
      註冊 | 登入 | 全文檢索 | 排行榜  

» JWorld@TW » Java 技巧文件  

按列印兼容模式列印這個話題 列印話題    把這個話題寄給朋友 寄給朋友    訂閱主題
reply to topicthreaded modego to previous topicgo to next topic
本主題所含的標籤
作者 如何重覆執行webcam
larry780216





發文: 1
積分: 0
於 2010-09-06 17:43 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
我的webcam主要功能在於 物體影像有移動時會拍攝四張照片
拍完這四張會合成一張在pushmail
但是 當拍攝四張結束時我的webcam就會停止不動
我用了無窮迴圈執行webcam都會出現錯誤
我想要拍完四張合成後 可以休息一段時間 webcam再繼續啟動
我的錯誤訊息只看的懂 "我的攝影機還在被使用中"
錯誤訊息:
java.io.IOException: Capture device in use
Exception in thread "main" java.lang.NullPointerException
  at FrameGrabber.setup(FrameGrabber.java:217)
  at FrameGrabber.<init>(FrameGrabber.java:78)
  at webcamCapture.<init>(webcamCapture.java:61)
  at webcamCapture.main(webcamCapture.java:38)

附上程式碼 主程式webcamCapture
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import java.io.*;
import java.lang.*;
import java.util.*;
 
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.media.*;
import javax.media.util.*;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.protocol.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
public class webcamCapture extends Frame
{
  private final String JPGfileName="0000";
 
  private BufferedImage imageOrg;
  private BufferedImage imageExe;
  private BufferedImage photo;
  private FrameGrabber webcam;
  private int threshold = 500;
  private Color on = Color.white;
  private Color off = Color.black;
  private static mailpush mail;
  private difference diffImage;
  private static picture pic;
  
  public static void main(String[] args) throws AddressException, MessagingException, InterruptedException, EOFException
  {
    
    while(true){  //這裡需要使用無窮 卻都錯誤
    webcamCapture web=  new webcamCapture();
 
picture tp = new picture();
        tp.show();
        Thread.sleep(3000);
       
        tp.dispose();
        web.dispose();
        
        //mail=new mailpush();
        //mail.run();
    
  }
  }
  public webcamCapture() throws AddressException, MessagingException, InterruptedException, EOFException
  {
    
    addWindowListener(new WindowListener());
    setTitle("Webcam Capture");
    
    webcam = new FrameGrabber();
    webcam.start();
    
    imageOrg = webcam.getBufferedImage();
    setSize(imageOrg.getWidth(this)+8,imageOrg.getHeight(this)+34);
    setLocation(350,350);
    setVisible(true);
    setBackground(Color.white);
//    difference diffImage=new difference(imageOrg);
    diffImage=new difference(imageOrg);
 
//    getContentPane().setLayout(null);
 
//    show();
    int i =0;  
    while(true){
      
      imageOrg = webcam.getBufferedImage();
//      diffImage.doProcess(imageOrg);
      imageExe=diffImage.doProcess(imageOrg);
 
      repaint();
      
      
      if(diffImage.movementWarning(100))
      {        
        fileSave save=new fileSave(imageOrg);
        i++;
        System.out.println(i);
        Thread.sleep(1000);
        if(i==4)   
          
          break;
        
      }
      
      
      
    }
    webcam.setEND(4);  
    
    //webcam.stop();      
    
}
 
  public void update(Graphics g)
  {
 
    if (imageExe != null)
    {
      g.drawImage(imageExe,4,30,this);
 
    }
 
  }
 
  class WindowListener extends WindowAdapter
  {
 
    public void windowdispose(WindowEvent e)
    {
      System.exit(0);
    }
 
  }
 
}
 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/**
 *JMF/Webcam Frame Grabber Demo
 *
 * @author S.Ritter24.01.2002
 * @version 1.0
 *
 *ALL EXAMPLES OF CODE AND/OR COMMAND-LINE INSTRUCTIONS ARE BEING
 *PROVIDED BY SUN AS A COURTESY, "AS IS," AND SUN DISCLAIMS ANY AND
 *ALL WARRANTIES PERTAINING THERETO, INCLUDING ANY WARRANTIES OF
 *MERCHANTABILTY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *SUN IS NOT LICENSING THIS EXAMPLE FOR ANY USE OTHER THAN FOR THE
 *EDUCATIONAL PURPOSE OF SHOWING THE FUNCTIONALITY CONTAINED
 *THEREIN, BY WAY OF EXAMPLE.
 **/
 
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import javax.media.*;
import javax.media.control.*;
import javax.media.protocol.*;
import javax.media.util.*;
import javax.media.format.*;
 
/**
 *Frame grabber class
 **/
public class FrameGrabber extends Thread implements ControllerListener
{
  /*Default device name and format parameters to use if no properties file
   *is provided
   */
  private final static String DEFAULT_DEV_NAME ="vfw:Microsoft WDM Image Capture (Win32):0";
  private final static String DEFAULT_X_RES = "160";
  private final static String DEFAULT_Y_RES = "120";
  private final static String DEFAULT_DEPTH = "24";
public int end=0;
  private Properties videoProperties;
 
  /*These objects are used for controlling access via wait and notify to
   *ensure that the processor has been realised and the second thread has
   *completed it's startup
  */
  private Object stateLock = new Object();
  private Object runLock = new Object();
 
  private Processor deviceProc = null;
  private PushBufferStream camStream;
  private PushBufferDataSource source = null;
  private BufferToImage converter;
  private Image currentImage;
  private boolean threadRunning = false;
 
  private MediaLocator loc;
  private DataSource formattedSource;
  private boolean FormatRGB = true;
 
  /**
   *Constructor
   *
   *
   * @throws FrameGrabberException If we can't start up the camera
   **/
//  public FrameGrabber() throws FrameGrabberException
  public FrameGrabber()
  {
    /*If the user chooses the no parameter form of the constructor we
     *try to get the video property file name from the properties
     *passed on the command line
     */
    //format=YUV 
    String videoPropFile = "C:/Users/larry/workspace/webcam1/src/video.properties";
    //System.getProperty("video.properties", "video.properties");
 
    setup(videoPropFile);
  }
public void setEND(int a){
  
  this.end=a;
}
  /**
   *Constructor
   *
   * @param videoPropFile The name of the video properties file
   * @throws FrameGrabberException If we can't start up the camera
   **/
//  public FrameGrabber(String videoPropFile) throws FrameGrabberException
  public FrameGrabber(String videoPropFile)
  {
    setup(videoPropFile);
  }
 
  /**
   *Setup method.Configures webcam and JMF ready to get images
   *
   * @param videoPropFile The name of the video properties file
   * @throws FrameGrabberException If we can't start up the camera
   **/
//  private void setup(String videoPropFile) throws FrameGrabberException
  private void setup(String videoPropFile)
  {
    videoProperties = new Properties();
 
    if (videoPropFile != null)
    {
      try
      {
        FileInputStream fis = new FileInputStream(new File(videoPropFile));
        videoProperties.load(fis);
      }
      catch (IOException ioe)
      {
        System.out.println("Unable to access video properties");
        System.out.println(ioe.getMessage());
      }
    }
 
    Dimension viewSize = null;
    int viewDepth = 0;
 
    String cameraDevice=videoProperties.getProperty("device-name", DEFAULT_DEV_NAME);
 
    /*Get the parameters for the video capture device from the properties
     *file.If not defined use default values
     */
    try
    {
      String pValue =  videoProperties.getProperty("resolution-x", DEFAULT_X_RES);
      int xRes = Integer.parseInt(pValue);
      pValue = videoProperties.getProperty("resolution-y", DEFAULT_Y_RES);
      int yRes = Integer.parseInt(pValue);
      viewSize = new Dimension(xRes, yRes);
      pValue = videoProperties.getProperty("colour-depth", DEFAULT_DEPTH);
      viewDepth = Integer.parseInt(pValue);
      FormatRGB=videoProperties.getProperty("format").equals("RGB");
//      System.out.println("FormatRGB="+FormatRGB);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("Bad numeric value in video properties file");
      System.exit(1);
    }
 
    /*Try to get the CaptureDevice that matches the name supplied by the
     *user
     */
    CaptureDeviceInfo device = CaptureDeviceManager.getDevice(cameraDevice);
 
//    if (device == null)throw new FrameGrabberException("No device found [ " +cameraDevice + "]");
 
    VideoFormat userFormat = null;
    Format[] cfmt = device.getFormats();
 
    /*Find the format that the user has requested (if available)*/
//    System.out.println("device format="+cfmt.length);
    for (int i = 0; i < cfmt.length; i++)
    {
//      System.out.println("cfmt["+i+"]="+cfmt[i]);
      if (FormatRGB && cfmt[i] instanceof RGBFormat)
      {
        userFormat = (RGBFormat)cfmt[i];
        Dimension d = userFormat.getSize();
        int bitsPerPixel = ((RGBFormat)userFormat).getBitsPerPixel();
//        System.out.println("bitsPerPixel="+bitsPerPixel);
 
        if (viewSize.equals(d) && bitsPerPixel == viewDepth)
        break;
 
        userFormat = null;
      }else if(cfmt[i] instanceof YUVFormat) {
        userFormat = (YUVFormat)cfmt[i];
        Dimension d = userFormat.getSize();
        if (viewSize.equals(d))
          break;
        userFormat = null;
      }
    }
 
    /*Throw an exception if we can't find a format that matches the
     *user's criteria
     */
//    if (userFormat == null)throw new FrameGrabberException("Requested format not supported");
 
    /*To use this device we need a MediaLocator*/
    loc = device.getLocator();
 
//    if (loc == null)throw new FrameGrabberException("Unable to get MediaLocator for device");
 
    formattedSource = null;
 
    /*Now create a dataSource for this device and set the format to
     *the one chosen by the user.
     */
    try
    {
      formattedSource = Manager.createDataSource(loc);
    }
    catch (IOException ioe)
    {
//      throw new FrameGrabberException("IO Error creating dataSource");
    }
    catch (NoDataSourceException ndse)
    {
//      throw new FrameGrabberException("Unable to create dataSource");
    }
 
    /*Setting the format is rather complicated.Firstly we need to get
     *the format controls from the dataSource we just created.In order
     *to do this we need a reference to an object implementing the
     *CaptureDevice interface (which DataSource objects can).
     */
//    if (!(formattedSource instanceof CaptureDevice))throw new FrameGrabberException("DataSource not a CaptureDevice");
 
    FormatControl[] fmtControls =((CaptureDevice)formattedSource).getFormatControls();
 
//    if (fmtControls == null || fmtControls.length == 0)throw new FrameGrabberException("No FormatControl available");
 
    Format setFormat = null;
 
    /*Now we need to loop through the available FormatControls and try
     *to set the format to the one we want.According to the documentation
     *even though this may appear to work, it may fail later on.Since
     *we know that the format is supported we hope that this won't happen
     */
//    System.out.println("fmtControls.length="+fmtControls.length);
    for (int i = 0; i < fmtControls.length; i++)
    {
//      System.out.println(fmtControls[i]);
      if (fmtControls[i] == null)
      continue;
 
      if ((setFormat = fmtControls[i].setFormat(userFormat)) != null)
      break;
    }
//    fmtControls[0].setFormat(cfmt[9]);
 
    /*Throw an exception if we couldn't set the format*/
//    if (setFormat == null)throw new FrameGrabberException("Failed to set camera format");
 
    /*Connect to the DataSource*/
    try
    {
      formattedSource.connect();
    }
    catch (IOException ioe)
    {
//      throw new FrameGrabberException("Unable to connect to DataSource");
    }
 
    /*Since we don't want to display the output to the user at this stage
     *we use a processor rather than a player to get frame access
     */
    try
    {
      deviceProc = Manager.createProcessor(formattedSource);
    }
    catch (IOException ioe)
    {
//      throw new FrameGrabberException("Unable to get Processor for device: " +ioe.getMessage());
    }
    catch (NoProcessorException npe)
    {
//      throw new FrameGrabberException("Unable to get Processor for device: " +npe.getMessage());
    }
 
    /*In order to use the controller we have to put it in the realized
     *state.We do this by calling the realize method, but this will
     *return immediately so we must register a listener (this class) to
     *be notified when the controller is ready.
     */
    deviceProc.addControllerListener(this);
    deviceProc.realize();
 
    /*Wait for the device to send an event telling us that it has
     *reached the realized state
     */
    while (deviceProc.getState() != Controller.Realized)
    {
      synchronized (stateLock)
      {
        try
        {
          stateLock.wait();
        }
        catch (InterruptedException ie)
        {
//          throw new FrameGrabberException("Failed to get to realized state");
        }
      }
    }
 
    deviceProc.start();
 
    /*Get access to the PushBufferDataSource which will provide us with
     *a means to get at the frame grabber
     */
    try
    {
      source = (PushBufferDataSource)deviceProc.getDataOutput();
    }
    catch (NotRealizedError nre)
    {
      /*Should never happen*/
//      throw new FrameGrabberException("Processor not realized");
    }
 
    /*Now we can retrieve the PushBufferStreams that will enable us to
     *access the data from the camera
     */
    PushBufferStream[] streams = source.getStreams();
    camStream = null;
 
//    System.out.println("streams.length="+streams.length);
    for (int i = 0; i < streams.length; i++)
    {
      /*Use the first Stream that is RGBFormat (there should be only one*/
//      System.out.println("streams[i]="+streams[i]+" streams[i].getFormat()="+streams[i].getFormat());
      if (streams[i].getFormat() instanceof RGBFormat)
      {
        camStream = streams[i];
        RGBFormat rgbf = (RGBFormat)streams[i].getFormat();
        converter = new BufferToImage(rgbf);
        break;
      }else if(streams[i].getFormat() instanceof YUVFormat){
        camStream = streams[i];
        converter = new BufferToImage((VideoFormat)streams[i].getFormat());
        break;
      }
    }
//    System.out.println(camStream+" "+camStream.getFormat());
    if(userFormat == null) System.out.print("Format no match ... ");
    if(camStream.getFormat() instanceof YUVFormat) System.out.print("YUV "+((YUVFormat)camStream.getFormat()).getSize().width+"x"+((YUVFormat)camStream.getFormat()).getSize().height);
    else if(camStream.getFormat() instanceof RGBFormat) System.out.print("RGB "+((RGBFormat)camStream.getFormat()).getSize().width+"x"+((RGBFormat)camStream.getFormat()).getSize().height);
    System.out.println(" Capture device ready");
  }
 
  /**
   *Get an image from the camera as an AWT Image object
   *
   * @returns The current image from the camera
   **/
  public Image getImage()
  {
    /*Since we are using a second thread to grab the images from the webcam
     *we need to ensure that an image has been aquired.
     *We do this by using a flag which will be set to true in the run()
     *method.If this is false we wait until the run method notifies us
     *that there is an image to collect
     */
    
    while (threadRunning == false)
    {
    
      synchronized (runLock)
      {
        try
        {
          runLock.wait();
        }
        catch (InterruptedException ie)
        {
          // Ignore
        }
      }
      
      
    }
 
    return accessInternalImage(null);
  }
 
  /**
   *Get an image from the camera as a BufferedImage
   *
   * @returns The current image from the camera
   **/
  public BufferedImage getBufferedImage()
  {
    return (BufferedImage)getImage();
  }
 
  /**
   *Run method for Thread class
   **/
  public void run()
  {
 
    System.out.println("Capture thread starting...");
    Buffer b = new Buffer();
    
    /*Simply loop forever grabbing images from the web cam and storing
     *them so that the user can retrieve them when required.
     */
    while (true)
    {      
      
      try
      {
        camStream.read(b);
      }
      catch (Exception e)
      {
        //Ignore.Nothing we can really do about this
      }
 
      Image i = converter.createImage(b);
      accessInternalImage(i);
 
      /*If this is the first image we've collected we need to advertise
       *to the main thread that there is an image ready and then notify
       *the main thread in case it is waiting on the image
       */
      if (!threadRunning)
      {
        threadRunning = true;
 
        synchronized (runLock)
        {
          runLock.notifyAll();
          
        }      
 
      }
      
      if (end==4){
        
        System.out.println(end);
      
            break;}
    }
    
  }
 
  /**
   *Method called when a controller event is received (implements
   *ControllerListener interface)
   *
   * @param ce The controller event
   **/
  public void controllerUpdate(ControllerEvent ce)
  {
    if (ce instanceof RealizeCompleteEvent)
    {
      synchronized (stateLock)
      {
        stateLock.notifyAll();
      }
    }
  }
 
  /**
   *Method that controls access to the global image variable.This ensures
   *that there is no confusion over one thread reading an image whilst
   *another is writing to it
   *
   * @param image The image to store (null indicates retrieval of the image)
   * @return The image (if the parameter was null)
   **/
  private synchronized Image accessInternalImage(Image image)
  {
    if (image == null)
    {
      return currentImage;
    }
 
    currentImage = image;
    return null;
  }
 
  public MediaLocator getMediaLocator()
  {
    return(loc);
  }
 
  public DataSource getDataSource()
  {
    return(formattedSource);
  }
 
  public Processor getProcessor()
  {
    return(deviceProc);
  }
}
 


附件有全部程式碼 我需要拍攝四張之後 合成完 mailpush後 webcam可以繼續拍攝

在這裡先感謝大大看完這些字

Copy (2) of webcam1.rar (41.3k)


reply to postreply to post
作者 Re:如何重覆執行webcam [Re:larry780216]
hiuwa





發文: 1
積分: 0
於 2011-07-05 12:38 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
thank you Blush

reply to postreply to post
» JWorld@TW »  Java 技巧文件

reply to topicthreaded modego to previous topicgo to next topic
  已讀文章
  新的文章
  被刪除的文章
Jump to the top of page

JWorld@TW 本站商標資訊

Powered by Powerful JuteForum® Version Jute 1.5.8