我希望能够在 python 3 和 Windows 中从网络摄像头拍照。有支持的模块吗?我尝试过pygame,但它只是linux和python 2,而VideoCapture只是python 2。
我一直在寻找同样的东西,但到目前为止我却发现了一个空白。这是我到目前为止所拥有的:
2.7 3.2 3.3 3.4 Linux WIN32 -------------------------------------------------- ----- OpenCV 是 - - - 是 是 PyGame 是是是是是是是是是 SimpleCV 是 - - - 是 是 视频捕捉 是 - - - - 是
资源
14年7月8日
Pygame 3.4 版本。已发布
http://www.youtube.com/watch?v=SqmSpJfN7OE
http://www.lfd.uci.edu/~gohlke/pythonlibs/
您可以下载“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")
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()
这是 Pygame 代码,它将使用 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()