最近有個數(shù)據(jù)需要分類處理,是一批含有白天跟夜晚的視頻數(shù)據(jù),需要進(jìn)行區(qū)分開來,單個視頻嚴(yán)格是只有一個場景的,比如說白天整個視頻就一定是白天,因為數(shù)據(jù)量有些大,幾千個視頻,所以就使用代碼簡單區(qū)分下,最后運行結(jié)果還可以,準(zhǔn)確率百分之80十多,當(dāng)然本批數(shù)據(jù)不用太嚴(yán)格,所以代碼區(qū)分完全夠了。
import cv2
import numpy as np
import os,time
import shutil
def GetImgNameByEveryDir(file_dir,videoProperty):
FileNameWithPath = []
FileName = []
FileDir = []
for root, dirs, files in os.walk(file_dir):
for file in files:
if os.path.splitext(file)[1] in videoProperty:
FileNameWithPath.append(os.path.join(root, file)) # 保存圖片路徑
FileName.append(file) # 保存圖片名稱
FileDir.append(root[len(file_dir):]) # 保存圖片所在文件夾
return FileName,FileNameWithPath,FileDir
def img_to_GRAY(img,pic_path):
#把圖片轉(zhuǎn)換為灰度圖
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#獲取灰度圖矩陣的行數(shù)和列數(shù)
r,c = gray_img.shape[:2]
piexs_sum=r*c #整個圖的像素個數(shù)
#遍歷灰度圖的所有像素
#灰度值小于60被認(rèn)為是黑
dark_points = (gray_img 60)
target_array = gray_img[dark_points]
dark_sum = target_array.size #偏暗的像素
dark_prop=dark_sum/(piexs_sum) #偏暗像素所占比例
if dark_prop >=0.60: #若偏暗像素所占比例超過0.6,認(rèn)為為整體環(huán)境黑暗的圖片
return 1
else:
return 0
if __name__ =='__main__':
path="C:\\Users\\Administrator\\Desktop\\cut_video"
new_path=path+"\\DarkNight"
if not os.path.exists(new_path):
os.mkdir(new_path)
FileName,FileNameWithPath,FileDir=GetImgNameByEveryDir(path,'.mp4')
for i in range(len(FileNameWithPath)):
video_capture = cv2.VideoCapture(FileNameWithPath[i])
video_size = (int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)),int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
video_fps = int(video_capture.get(5))
start_fps=2*video_fps #從2秒開始篩選
end_fps=6*video_fps #6秒結(jié)束
avg_fps=end_fps-start_fps #總共fps
video_capture.set(cv2.CAP_PROP_POS_FRAMES, start_fps) #設(shè)置視頻起點
new_paths=new_path+"\\"+FileName[i]
j=0
count=0
while True:
success,frame = video_capture.read()
if success:
j += 1
if(j>=start_fps and j = end_fps):
flag=img_to_GRAY(frame,FileNameWithPath[i])
if flag==1:
count+=1
elif(j>end_fps):
break
else:
break
print('%s,%s'%(count,avg_fps))
if count>int(avg_fps*0.48): #大于fps50%為黑夜
print("%s,該視頻為黑夜"%FileNameWithPath[i])
video_capture.release() #釋放讀取的視頻,不占用視頻文件
time.sleep(0.2)
shutil.move(FileNameWithPath[i],new_paths)
else:
print("%s,該視頻為白天"%FileNameWithPath[i])
到此這篇關(guān)于opencv 分類白天與夜景視頻的方法的文章就介紹到這了,更多相關(guān)opencv 分類白天與夜景視頻內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!