简体   繁体   English

使用 Java 或 Python 从我的网络摄像头捕获单个图像

[英]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).我想用 Java 或 Python(最好是 Java)来做这件事。 I want something that will work on both 64-bit Win7 and 32-bit Linux.我想要一些可以在 64 位 Win7 和 32 位 Linux 上运行的东西。

EDIT: I use Python 3.x, not 2.x编辑:我使用 Python 3.x,而不是 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. Java 媒体框架已经过时了。 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)我宁愿不使用 JavaCV,但如果我绝对必须,我想确切地知道我需要 OpenCV 库中的哪些文件,以及如何在不包含整个库的情况下使用这些文件(最好不要将这些文件粘贴在任何类型的文件中) PATH。所有内容都应包含在一个目录中)
  • 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如果需要,我可以在 64 位 Win7 计算机上使用 Eclipse,但我也必须能够在 32 位 Linux 上编译和使用它
  • 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. EDIT2:我能够使用 Python 2.7 和 pygame 1.9.1 在 Linux 上获得 Froyo 的 pygame 示例。 the pygame.camera.camera_list() call didn't work, but it was unnecessary for the rest of the example. pygame.camera.camera_list() 调用不起作用,但对于示例的其余部分来说是不必要的。 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.但是,我不得不调用 cam.set_controls()(您可以在此处找到文档http://www.pygame.org/docs/ref/camera.html )来提高亮度,以便我实际上可以看到我捕获的图像。

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.此外,我需要在第一对调用中实际保存的图像之前调用 cam.get_image() 和 pygame.image.save() 方法三次。 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.基本上,不是调用 cam.get_image() 一次,而是每次我想捕获图像时都必须调用它三遍。 Then and only then did I call pygame.image.save().然后我才调用 pygame.image.save()。

Unfortunately, as stated below, pygame.camera is only supported on Linux.不幸的是,如下所述,pygame.camera 仅在 Linux 上受支持。 I still don't have a solution for Windows.我仍然没有适用于 Windows 的解决方案。

@thebjorn has given a good answer. @thebjorn 给出了很好的答案。 But if you want more options, you can try OpenCV, SimpleCV.但是如果你想要更多的选择,你可以尝试 OpenCV、SimpleCV。

using SimpleCV (not supported in python3.x):使用SimpleCVpython3.x不支持):

from SimpleCV import Image, Camera

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

using OpenCV :使用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 :使用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 :安装OpenCV

install python-opencv bindings, numpy

Install SimpleCV :安装SimpleCV

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

get latest version of SimpleCV获取最新版本的SimpleCV

Install pygame :安装pygame

install pygame

On windows it is easy to interact with your webcam with pygame:在 Windows 上,使用 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我还没有尝试在 linux 上使用 pygame(我所有的 linux boxen 都是没有 X 的服务器),但是这个链接可能会有所帮助http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-在 linux 上

Some time ago I wrote simple Webcam Capture API which can be used for that.前段时间我编写了简单的网络摄像头捕获 API ,可以用于此目的。 The project is available on Github.该项目可在 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();
}
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()

I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow.我基于 DirectShow 编写了一个完全用 Python 从网络摄像头捕获图像的工具。 You can find it here: https://github.com/andreaschiavinato/python_grabber .你可以在这里找到它: 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:您可以通过以下方式使用整个应用程序或仅使用 dshow_graph.py 中的 FilterGraph 类:

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()

It can be done by using ecapture First, run可以通过使用ecapture来完成首先,运行

pip install ecapture

Then in a new python script type:然后在一个新的 python 脚本类型中:

    from ecapture import ecapture as ec

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

More information from this link来自此链接的更多信息

I am able to achieve it, this way in Python:我能够以这种方式在 Python 中实现它:

Please install PyAutoGUI请安装PyAutoGUI

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

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

time.sleep(1) # Required !
img=pg.screenshot() # Take screenshot using PyAutoGUI's function
time.sleep(1) # Required !
img.save(<Your File Path HERE with extenstion>) # Save image screenshot at desired location on your computer

#Close the camera
subprocess.run('Taskkill /IM WindowsCamera.exe /F', shell=True) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM