項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【OpenCV】OpenCV 利用 python OpenCV 將一部影片拆成一張張圖片 | last update: 2024/04/24

【OpenCV】利用 python OpenCV 將一部影片拆成一張張圖片

很多時候,我們會需要將一部影片拆成一張張的圖片,
我們可以用 OpenCV 實現這件事情,
以下為範例程式碼。

如果要自己運用,需要修改的部分:

  • video_path = ‘.mp4′
    • 影片的路徑,需改為影片名稱。
  • output_folder = ‘./output/’
    • 影片轉換圖片後,圖片的輸出位置。
      (注意!資料夾會自己建立,但如果資料夾已存在,會刪掉資料夾內所有東西!)

執行後等待結果,我們就會在同一個目錄底下 output 的資料夾拿到我們要的所有圖片了。


import os
import cv2

video_path = '<your_file>.mp4'
output_folder = './output/'

if os.path.isdir(output_folder):
    print("Delete old result folder: {}".format(output_folder))
    os.system("rm -rf {}".format(output_folder))
os.system("mkdir {}".format(output_folder))
print("create folder: {}".format(output_folder))

vc = cv2.VideoCapture(video_path)
fps = vc.get(cv2.CAP_PROP_FPS)
frame_count = int(vc.get(cv2.CAP_PROP_FRAME_COUNT))
print(frame_count)
video = []

for idx in range(frame_count):
    vc.set(1, idx)
    ret, frame = vc.read()
    height, width, layers = frame.shape
    size = (width, height)

    if frame is not None:
        file_name = '{}{:08d}.jpg'.format(output_folder,idx)
        cv2.imwrite(file_name, frame)

    print("\rprocess: {}/{}".format(idx+1 , frame_count), end = '')
vc.release()

一些我搜尋用的關鍵字

  • get images from video

Reference

⭐Python OpenCV 相關文章整理⭐:
⭐基礎知識篇⭐:
1.【OpenCV】1 – 安裝 python OpenCV install 電腦中圖片的基本概念總整理 (附錄:OpenCV 快速測試用程式碼)
2.【OpenCV】2 – OpenCV 圖片的讀取、顯示、存檔 (load, show, save),附贈簡易理解「相對路徑」與「絕對路徑」
3.【OpenCV】OpenCV 利用 python OpenCV 查詢 image 大小, img shape sample code (內附範例程式碼)
⭐基本圖像處理篇⭐:
1.【OpenCV】OpenCV 利用 python OpenCV 縮放圖片 image 大小, cv2 resize (內附程式碼)
2.【OpenCV】3 – python OpenCV 的剪裁、旋轉、縮放 (crop, rotate, resize)
3.【OpenCV】4 – 運用 OpenCV 調整光線 (modify brightness, intensity)
4.【OpenCV】5 – 運用 OpenCV 調整亮度、飽和度(透過轉移至 HLS 顏色空間) modify lightness, saturation
5.【OpenCV】6 – 運用 OpenCV 調整色調(冷色系/暖色系)、色溫(白平衡)modify color temperature, white balance
6.【OpenCV】7 – 運用 OpenCV 為圖片增加一些顆粒感 (增加高斯噪點) add gaussian noise
7.【OpenCV】8 – 運用 OpenCV 改變圖片的對比度 modify contrast (內含:網路上常見錯誤調整對比度方式的分析)
8.【OpenCV】9 – 運用 OpenCV 降低圖片的高光 reduce highlights
9.【OpenCV】11 – OpenCV 建立新空白圖、畫點、畫圓 create new pictures, draw points and draw circle
10.【OpenCV】12 – 運用 OpenCV 畫線、畫矩形、畫橢圓 draw lines, draw rectangle, draw ellipse
11.【OpenCV】13 – 運用 OpenCV 在圖片上寫文字、查色碼、顯示色碼顏色 write text, get and show RGB Color Code
⭐進階圖像處理篇⭐:
1.【OpenCV】14 – 運用 OpenCV 顯示圖片直方圖、分離與合併RGB通道 show histogram, split, merge RGB channel
2.【OpenCV】15 – OpenCV 當然也有像 ps 圖層的功能! 什麼?圖片也能加減法?! Add, Subtract, AddWeighted
3.【OpenCV】16 – 運用 OpenCV 幫助我們找圖片的輪廓(高斯模糊、Canny) cv2.GaussianBlur, cv2.Canny
4.【OpenCV】17 – 運用 OpenCV 的終極圖層處理大全, 想P圖該怎麼P (bitwise_or, and, xor, not, addWeighted)
5.【OpenCV】18 – 運用 OpenCV 做圖片二值化,產生黑白的圖片吧!cv2.threshold 各種選擇參數大全
6.【OpenCV】19 – OpenCV 的圖片自適應二值化,產生更好效果的黑白圖片!cv2.adaptiveThreshold
7.