在Windows下用Python 3拍摄网络摄像头照片
我想用Python 3在Windows上从网络摄像头拍照。有没有什么模块可以支持这个功能?我试过pygame,但它只支持Linux和Python 2,而VideoCapture也只支持Python 2。
4 个回答
这里有一段Pygame的代码,可以用来通过网络摄像头拍照。到2023年为止,Pygame支持Windows系统和Python 3。
不过有个缺点,就是在调用start()
方法后,摄像头大约需要0.6到0.7秒才能准备好。在这段时间里,它返回的都是全黑的图像,而不是照片。你可以选择在调用get_image()
拍照之前加一个1秒的暂停,或者运行一些代码来检查返回的图像是否是全黑的(我在示例中有这段代码,但被注释掉了)。
import pygame.camera, pygame.image, time
pygame.camera.init()
all_webcams = pygame.camera.list_cameras()
webcam = pygame.camera.Camera(all_webcams[0]) # Use the first found webcam.
webcam.start() # Initialize the webcam.
time.sleep(1) # Wait for the camera to get ready.
photo = webcam.get_image() # Take a photo from the webcam.
# Uncomment the following and remove the previous two lines to have
# the webcam keep taking photos until it finds one that isn't all black.
#while True:
# photo = webcam.get_image() # Take a photo from the webcam.
#
# # Check if the photo is all black because the webcam wasn't ready:
# all_black = True
# for x in range(photo.get_width()):
# for y in range(photo.get_height()):
# if photo.get_at((x, y)) != (0, 0, 0, 255):
# all_black = False
# break
# if not all_black:
# break # The webcam was ready and took a real photo.
# else:
# time.sleep(0.1) # Wait before trying to take another photo.
pygame.image.save(photo, "photo.png") # You can also use .jpg or .bmp.
pygame.camera.quit()
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,不知道该如何解决。比如,有人可能在使用某个特定的功能时,发现它没有按照预期工作。这时候,我们就需要去查找相关的信息,看看有没有人遇到过类似的问题,以及他们是如何解决的。
在这个过程中,StackOverflow是一个非常有用的地方。这里有很多程序员分享他们的经验和解决方案。你可以在这里提问,或者搜索之前的问题,看看有没有人已经回答过你的疑问。
总之,遇到问题时,不要害怕去寻求帮助,利用好这些资源,可以让你更快地找到解决方案。
import cv2
# Open the device at the ID 0
cap = cv2.VideoCapture(0)
#Check whether user selected camera is opened successfully.
if not (cap.isOpened()):
print("Could not open video device")
#To set the resolution
cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 480)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('preview',frame)
#Waits for a user input to quit the application
if cv2.waitKey(1) & 0xFF == ord('q'):
#break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
我一直在寻找同样的东西,但到现在为止还没有找到。这是我目前得到的:
2.7 3.2 3.3 3.4 LINUX WIN32 ------------------------------------------------------- OpenCV YES - - - YES YES PyGame YES YES YES YES YES YES SimpleCV YES - - - YES YES VideoCapture YES - - - - YES
资源
- opencv.org/downloads.html
- pygame.info/downloads/
- simplecv.org/download
- videocapture.sourceforge.net/
2014年7月8日
Pygame 3.4版本发布了
你可以下载“pygame‑1.9.2a0.win32‑py3.4.exe”这个文件
在Python 3.4中从网络摄像头拍照(在Windows 7上测试)代码 [1]
import pygame
import pygame.camera
pygame.camera.init()
cam = pygame.camera.Camera(0,(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")
参考链接
[1] 如何在Java或Python中从我的网络摄像头捕获单张图片