50

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.

Matthew G
  • 1,090
  • 2
  • 14
  • 23
  • 2
    Buffer and timing issues are always something you need to handle when dealing with the real world (capture devices included, e.g. http://stackoverflow.com/questions/5595658/python-video-capture-loop ). Even a simple on/off switch has these issues (see http://www.labbookpages.co.uk/electronics/debounce.html for a deeper explanation of both hardware and software solutions). – thebjorn Jun 19 '12 at 07:37
  • 1
    Would the content of this page answer your question by any chance? [How to use JavaCV in an applet](http://code.google.com/p/javacv/wiki/HowToMakeAnApplet) – Samuel Audet Jun 19 '12 at 07:50
  • 1
    See also: [How can I take camera images with Python?](http://stackoverflow.com/q/28418962/562769) – Martin Thoma Feb 09 '15 at 21:38

7 Answers7

84

@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
zvi
  • 3,677
  • 2
  • 30
  • 48
Froyo
  • 17,947
  • 8
  • 45
  • 73
  • Apparently stating this in the question isn't enough: 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) – Matthew G Jun 19 '12 at 05:39
  • OpenCV and SimpleCV are both HUGE. I do not want to have to install ALL of it – Matthew G Jun 19 '12 at 05:39
  • 2
    SimpleCV doesn't support python 3.x. OpenCV is huge. If you want you can use pygame. You could have used PIL, but it also does not support python 3.x – Froyo Jun 19 '12 at 05:45
  • 1
    http://stackoverflow.com/questions/3896286/image-library-for-python-3 PIL for python 3.x – Froyo Jun 19 '12 at 05:48
  • 1
    Also, pygame.camera only supports Linux. There isn't any Windows support at present. – Matthew G Jun 19 '12 at 05:49
  • what!? seriously ? I didn't know that. damn windows. you could do one thing for windows => use some software that captures and saves the image. call it via os.system() or subprocess.Popen() – Froyo Jun 19 '12 at 05:54
  • 2
    pygame.camera uses the [VideoCapture](http://videocapture.sourceforge.net/) module in pygame-1.9.2pre on Windows. See https://bitbucket.org/pygame/pygame/src/11d40f67485c/lib/_camera_vidcapture.py – cgohlke Jun 19 '12 at 07:16
  • 5
    It's `pygame.camera.list_cameras()`, not `pygame.camera.list_camera()`. – pasbi May 28 '17 at 09:59
  • Isn't the package name `opencv-python`, not `python-opencv`? – user1318499 Sep 10 '21 at 02:41
  • Please change `CV_WINDOW_AUTOSIZE` which doesn't work to `WINDOW_AUTOSIZE` which does. I can't edit it because there's a 6 character limit and this is only 3. – user1318499 Sep 10 '21 at 03:43
20

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

thebjorn
  • 26,297
  • 11
  • 96
  • 138
  • 1
    I've never used pygame before. I've downloaded the pygame-1.9.2a0.win32-py3.2.msi file from here http://www.pygame.org/download.shtml and installed it, then tried to run your code in a Python shell, but it didn't produce anything different to before I installed pygame. I don't mean to sound harsh, but please don't assume something that's easy for you is easy for me. I need baby steps because I know next to nothing about what I'm trying to do. – Matthew G Jun 19 '12 at 05:23
  • 1
    Also, VideoCapture doesn't support python-3.2 – Matthew G Jun 19 '12 at 05:36
  • @cgohlke that page has been a life saver a couple of times! – thebjorn Jun 19 '12 at 07:22
  • 2
    @MatthewG you should look in the Examples folder of VideoCapture for runnable examples, and read the (psychedelically colored) documentation: http://videocapture.sourceforge.net/html/VideoCapture.html – thebjorn Jun 19 '12 at 07:25
8
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()
ShivaGuntuku
  • 5,274
  • 6
  • 25
  • 37
  • How can I install cv2? –  May 20 '18 at 16:54
  • @Benoit.B.Mandelbrot install opencv version 2 or higher. follow this url to install on Linux enviroment https://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html – Sarasa Gunawardhana Jul 11 '18 at 07:32
  • 1
    Can you explain what `if cv2.waitKey(1)& 0xFF == ord('s'):` does? – Sledge Oct 02 '19 at 13:28
  • It means if CtlˆS is pressed. I suppose waitkey(1) is Ctl button (in Mac it is command key), and ord('s') stands for value for "s" character. – Leo Sep 10 '20 at 05:27
6

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();
}
markop
  • 75
  • 3
  • 11
Bartosz Firyn
  • 2,664
  • 2
  • 21
  • 18
2

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()
Andrea S.
  • 51
  • 3
  • Thanks for the feedback. I added an example code, but I cannot copy all the code of the class FilterGraph here because it's quite long. However now the answer looks like the one from Bartosz Firyn. – Andrea S. Jan 07 '19 at 16:34
2

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

Yfomnn
  • 17
  • 2
0

I am able to achieve it, this way in Python (Windows 10):

Please install PyAutoGUI

import pyautogui as pg #For taking screenshot
import time # For necessary delay
import subprocess 

# Launch Windows OS Camera
subprocess.run('start microsoft.windows.camera:', shell=True) 

time.sleep(2) # Required !
img=pg.screenshot() # Take screenshot using PyAutoGUI's function
time.sleep(2) # Required !
img.save(r"C:\Users\mrmay\OneDrive\Desktop\Selfie.PNG") # Save image screenshot at desired location on your computer

#Close the camera
subprocess.run('Taskkill /IM WindowsCamera.exe /F', shell=True) 
Mayur Patil
  • 139
  • 2
  • 5
  • On my windows 10 it is the only choice that works without the installation of outer components. Though my Python 3.9 requires the subprocess to be imported: import subprocess. – Roman Voronov Dec 23 '21 at 15:18