[java] Capturing a single image from my webcam in Java or Python

I want to capture a single image from my webcam and save it to disk. I want to do this in Java or Python (preferably Java). I want something that will work on both 64-bit Win7 and 32-bit Linux.

EDIT: I use Python 3.x, not 2.x

Because everywhere else I see this question asked people manage to get confused, I'm going to state a few things explicitly:

  • I do not want to use Processing
  • I do not want to use any language other than those stated above
  • I do want to display this image on my screen in any way, shape or form
  • I do not want to display a live video feed from my webcam on my screen, or save such a feed to my hard drive
  • The Java Media Framework is far too out of date. Do not suggest it.
  • I would rather not use JavaCV, but if I absolutely must, I want to know exactly which files from the OpenCV library I need, and how I can use these files without including the entire library (and preferably without sticking these files in any sort of PATH. Everything should be included in the one directory)
  • I can use Eclipse on the 64-bit Win7 computer if need be, but I also have to be able to compile and use it on 32-bit Linux as well
  • If you think I might or might not know something related to this subject in any way shape or form, please assume I do not know it, and tell me

EDIT2: I was able to get Froyo's pygame example working on Linux using Python 2.7 and pygame 1.9.1. the pygame.camera.camera_list() call didn't work, but it was unnecessary for the rest of the example. However, I had to call cam.set_controls() (for which you can find the documentation here http://www.pygame.org/docs/ref/camera.html) to up the brightness so I could actually see anything in the image I captured.

Also, I need to call the cam.get_image() and pygame.image.save() methods three times before the image I supposedly took on the first pair of calls actually gets saved. They appeared to be stuck in a weird buffer. Basically, instead of calling cam.get_image() once, I had to call it three times every single time I wanted to capture an image. Then and only then did I call pygame.image.save().

Unfortunately, as stated below, pygame.camera is only supported on Linux. I still don't have a solution for Windows.

This question is related to java python webcam image-capture javacv

The answer is


On windows it is easy to interact with your webcam with pygame:

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')

I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux


Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.

Example code:

Webcam webcam = Webcam.getDefault();
webcam.open();
try {
  ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
  e.printStackTrace();
} finally {
  webcam.close();
}

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink


I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow. You can find it here: https://github.com/andreaschiavinato/python_grabber.

You can use the whole application or just the class FilterGraph in dshow_graph.py in the following way:

from pygrabber.dshow_graph import FilterGraph
import numpy as np
from matplotlib.image import imsave

graph = FilterGraph()
print(graph.get_input_devices())
device_index = input("Enter device number: ")
graph.add_input_device(int(device_index))
graph.display_format_dialog()
filename = r"c:\temp\imm.png"
# np.flip(image, axis=2) required to convert image from BGR to RGB
graph.add_sample_grabber(lambda image : imsave(filename, np.flip(image, axis=2)))
graph.add_null_render()
graph.prepare()
graph.run()
x = input("Press key to grab photo")
graph.grab_frame()
x = input(f"File {filename} saved. Press key to end")
graph.stop()

import cv2
camera = cv2.VideoCapture(0)
while True:
    return_value,image = camera.read()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('image',gray)
    if cv2.waitKey(1)& 0xFF == ord('s'):
        cv2.imwrite('test.jpg',image)
        break
camera.release()
cv2.destroyAllWindows()

@thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.

using SimpleCV (not supported in python3.x):

from SimpleCV import Image, Camera

cam = Camera()
img = cam.getImage()
img.save("filename.jpg")

using OpenCV:

from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
    imshow("cam-test",img)
    waitKey(0)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image

using pygame:

import pygame
import pygame.camera

pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")

Install OpenCV:

install python-opencv bindings, numpy

Install SimpleCV:

install python-opencv, pygame, numpy, scipy, simplecv

get latest version of SimpleCV

Install pygame:

install pygame

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to webcam

How to run html file on localhost? Best way to access web camera in Java Capturing a single image from my webcam in Java or Python Displaying a webcam feed using OpenCV and Python How do I access my webcam in Python? How can I stream webcam video with C#? Capturing image from webcam in java?

Examples related to image-capture

Capturing a single image from my webcam in Java or Python How to capture UIView to UIImage without loss of quality on retina display

Examples related to javacv

Capturing a single image from my webcam in Java or Python