Python相机录制取帧存图
USB相机 键盘交互存图、直接录视频、从录制的视频中每10帧存取一张图
import os.path
import cv2 as cv
def Camera_image(raw_image_path):
cap = cv.VideoCapture(1, cv.CAP_DSHOW)
flag = cap.isOpened()
index = 1
while (flag):
ret, frame = cap.read()
cv.imshow("Capture", frame)
k = cv.waitKey(1) & 0xFF
if k == ord('s'): # 按下s键,进入下面的保存图片操作
cv.imwrite(raw_image_path + str(index) + ".jpg", frame)
print("raw_" + str(index) + ".jpg successfuly!")
print("-------------------------")
index += 1
elif k == ord('q'): # 按下q键,程序退出
break
cap.release()
cv.destroyAllWindows()
def Camera_video(raw_video_path):
cap = cv.VideoCapture(1)
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
writer = cv.VideoWriter( raw_video_path, cv.VideoWriter_fourcc(*'DIVX'), 20, (width, height))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame(stream end?). Exiting...")
break
frame = cv.flip(frame, 0)
writer.write(frame)
cv.imshow('frame', frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
writer.release()
cv.destroyAllWindows()
def grasp_frame(raw_video_path, video_name, raw_image_path):
cap = cv.VideoCapture(raw_video_path)
c = 1
timeF = 10
while (cap.isOpened()):
ret, frame = cap.read()
cv.imshow('frame', frame)
if(c%timeF == 0):
cv.imwrite(raw_image_path + video_name + "_" + str(c) + '.png', frame, [cv2.IMWRITE_PNG_COMPRESSION, 0])
c = c + 1
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
frame.release()
if __name__ == "__main__":
number = str(0) #录制新的video记得改编号
raw_video_path = os.path.join("raw_video/" + "video_"+ number +".avi") # Configuration Here
raw_video = raw_video_path.split('/')[-1]
video_name = raw_video.split('.')[0]
raw_image_path = "raw_image/"
#Camera_image(raw_image_path) # Real-time Camera save frame as image
Camera_video(raw_video_path) # Recording video
#grasp_frame(raw_video_path, video_name, raw_image_path) # Grasp frame from video then save it as image