如何實現在jupyter notebook中播放視訊(不停地展示圖片)
阿新 • • 發佈:2020-04-24
在解決影象處理問題的時候,可以利用opencv開啟視訊,並一幀一幀地show出來,但是要用到imshow(),需要本地的介面支援。
程式碼如下
# -*- coding:utf-8*- import cv2 capture = cv2.VideoCapture("D:\\dataset\\chip_gesture.ts") # 影象處理函式 def processImg(img): # 畫出一個框 cv2.rectangle(img,(500,300),(800,400),(0,255),5,1,0) # 上下翻轉 # img= cv2.flip(img,0) return img # 一幀幀地show while (capture.isOpened()): ret,frame = capture.read() if not ret: break result = processImg(frame) cv2.imshow('result',result) # esc鍵退出 if 0xFF & cv2.waitKey(30) == 27: break cv2.destroyAllWindows() capture.release()
但是當我們使用jupyter notebook來編寫python程式的時候,cv2.imshow()就不行了。
最終的解決辦法是使用ipython.display模組來解決。
from IPython.display import clear_output,Image,display,HTML import time import cv2 import base64 current_time = 0 # 影象處理函式 def processImg(img): # 畫出一個框 cv2.rectangle(img,0) # 顯示FPS global current_time if current_time == 0: current_time = time.time() else: last_time = current_time current_time = time.time() fps = 1. / (current_time - last_time) text = "FPS: %d" % int(fps) cv2.putText(img,text,100),cv2.FONT_HERSHEY_TRIPLEX,3.65,(255,0),2) return img def arrayShow(imageArray): ret,png = cv2.imencode('.png',imageArray) encoded = base64.b64encode(png) return Image(data=encoded.decode('ascii')) video = cv2.VideoCapture("/home/mvg/zmc/playgroud/遠大前程27.mp4") while(True): try: clear_output(wait=True) ret,frame = video.read() if not ret: break lines,columns,_ = frame.shape frame = processImg(frame) frame = cv2.resize(frame,(int(columns / 4),int(lines / 4))) img = arrayShow(frame) display(img) # 控制幀率 time.sleep(0.02) except KeyboardInterrupt: video.release()
最終的執行效果如下:
不過執行這段程式碼的時候,可能會提示iopub_data_rate_limit問題。如果使用配置檔案(推薦)來執行jupyter notebook的話,修改配置檔案
vim ~/.jupyter/jupyter_notebook_config.py
將c.NotebookApp.iopub_data_rate_limit = 10000000一行取消註釋,改變後面的資料傳輸上限值,10M差不多能播放視訊(有提示再修改上限)。
不使用配置檔案的話,在執行時加上引數
jupyter notebook –NotebookApp.iopub_data_rate_limit=10000000
以上這篇如何實現在jupyter notebook中播放視訊(不停地展示圖片)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。