京東豬臉識別比賽資料預處理:用Python將視訊每一幀提取儲存為圖片
阿新 • • 發佈:2019-01-04
最近參加京東的豬臉識別比賽,訓練集是30個視訊,需要將視訊的每一幀提取出來儲存為圖片,存入對應的資料夾(分類標籤)。
本例是直接呼叫了cv2 模組中的 VideoCapture。一次執行,大概10分鐘,就能得到預處理後的分類圖片了,具體程式碼如下。
視訊每一幀提取儲存為圖片程式碼
#! encoding: UTF-8
import os
import cv2
import cv
videos_src_path='/sata_disk/E_office/zhouhongli/pig/train'
images_save_path='/sata_disk/E_office/zhouhongli/pig/frame'
videos = os.listdir(videos_src_path)
videos = filter(lambda x: x.endswith('mp4'), videos)
for each_video in videos:
print each_video
# get the name of each video, and make the directory to save frames
each_video_name,_=each_video.split('.')
os.mkdir(images_save_path +'/'+ each_video_name)
each_video_save_full_path=os.path.join(images_save_path, each_video_name) + '/'
# get the full path of each video, which will open the video tp extract frames
each_video_full_path=os.path.join(videos_src_path, each_video)
cap=cv2.VideoCapture(each_video_full_path)
frame_count = 1
success = True
while(success):
success, frame=cap.read()
print 'Read a new frame: ', success
params = []
params.append(cv.CV_IMWRITE_PXM_BINARY)
params.append(1)
cv2.imwrite(each_video_save_full_path + each_video_name + "_%d.jpg" % frame_count, frame, params)
frame_count = frame_count+1
cap.release()
遞迴刪除檔案的問題
但有個問題,每一個視訊轉換得到的30個子資料夾裡,都有2952張圖片,但第2952張是空的,所以只有運用強大的Linux遞迴刪除符合條件的檔案了,我是這樣刪除滴。
zhouhongli@1080TI:~$ find . -name '*_2952.jpg' -size 0 -print0 |xargs -0 rm