我想用OpenCV从我的摄像头中获取并保存一些图像。这是我目前的代码:
import cv2
camera = cv2.VideoCapture(0)
for i in range(10):
return_value, image = camera.read()
cv2.imwrite('opencv'+str(i)+'.png', image)
del(camera)问题是,我不知道照片是什么时候拍摄的,所以很多照片都是模糊的。我的问题是:是否有一种方法可以在键盘键的点击下拍摄图像?
还有更好的方法来拍摄多个图像,而不是距离?
发布于 2020-03-10 04:10:38
这是一个简单的程序,用默认相机捕捉图像。另外,还可以检测到人脸。
import cv2
import sys
import logging as log
import datetime as dt
from time import sleep
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('s'):
check, frame = video_capture.read()
cv2.imshow("Capturing", frame)
cv2.imwrite(filename='saved_img.jpg', img=frame)
video_capture.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
img_new = cv2.imshow("Captured Image", img_new)
cv2.waitKey(1650)
print("Image Saved")
print("Program End")
cv2.destroyAllWindows()
break
elif cv2.waitKey(1) & 0xFF == ord('q'):
print("Turning off camera.")
video_capture.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
# Display the resulting frame
cv2.imshow('Video', frame)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()输出

此外,您还可以查看我的GitHub 代码
https://stackoverflow.com/questions/34588464
复制相似问题