opencv读取视频转换成一张张图片
class Opencv():
def __init__(self, vpath, savepath):
self.vpath = vpath
self.savepath = savepath
self.count = 1
def write_video(self):
cap = cv2.VideoCapture(self.vpath)
while True:
ret, frame = cap.read()
if not ret:
break
savepath = (r"%s\\%d.jpg" % (self.savepath, self.count))
cv2.imencode('.jpg', frame)[-1].tofile(savepath)
self.count += 1
cap.release()
cv2.destroyAllWindows()
def read_img(self):
self.count = 1
while True:
jpg_file = (r"C:\Users\宋增\Desktop\python相关文件\demo\%d.jpg" % self.count)
""" 路径 """
img0 = cv2.imdecode(np.fromfile(jpg_file, dtype=np.uint8), flags=-1)
""" 路径有中文 需要使用 读图片只接受英文路径"""
img = cv2.resize(img0, (666, 666))
""" 改变图片大小 """
txt = ("The %d picture" % self.count)
""" 显示内容 """
position = (150, 80)
"""puttext中 左下角文字显示位置 """
cv2.putText(img, text=txt, org=position, fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1.5, color=(0, 255, 0), thickness=2)
""" 在图片上显示文字,注意编码格式,只能是英文,其他语言需要转换"""
cv2.namedWindow('窗口', cv2.WINDOW_AUTOSIZE)
""" (cv2.WINDOW_AUTOSIZE) c窗口大小不可变"""
if img is None:
break
""" 判断img是否接受到图片 没有则跳出循环 """
cv2.imshow('窗口', img)
"""显示图片 """
c = cv2.waitKey()
""" 等待键盘输入 """
if c == ord('N'):
self.count += 1
""" 下一张健next """
if c == ord('U'):
self.count -= 1
""" 上一张健up """
if c == ord('E'):
break
""" 结束健end """
if __name__ == '__main__':
vpath = r'C:\Users\宋增\Videos\联想安卓视频\000.mp4'
""" 读视频的路径 """
savepath = r"C:\Users\宋增\Desktop\python相关文件\demo"
cv = Opencv(vpath, savepath)
""" 调用读视频,并且保存图片的函数 """
cv.read_img()
""" 读图片的函数 """