2017-08-19 21 views
1

把日期我要救VideoCapture在一定條件下, 所以我寫了下面的代碼:(OpenCV的),在文件名

date = datetime.now() 
    detector = dlib.get_frontal_face_detector() 
    cap = cv2.VideoCapture(1) #I use second camera 
    global count, no_face 
    total_number = 0 
    count = 0 
    no_face = 0 
    num_bad_posture = 0 
    not_detected_posture = 0 
    while True: 

     ret, frame = cap.read() 
     frame = cv2.resize(frame,None,fx=sf,fy=sf, interpolation=cv2.INTER_AREA) 
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
     dets = detector(gray,1) 

     if not dets: 
       print('no face') 
       no_face += 1 
       if no_face > 15: 
        print('no face!! for real!!') 
        now = str(date.now()) 
        not_detected = cv2.resize(frame,None,fx=5,fy=5,interpolation = cv2.INTER_CUBIC) 
        not_detected_posture += 1 
        print(type(now)) 
        cv2.imwrite('./images/non_detected/non_detected({0},{1}).jpg'. format(not_detected_posture,now),not_detected) 
        no_face=0 
     for i, d in enumerate(dets): 
       no_face = 0 
       w = d.width() 
       h = d.height() 
       x = d.left() 
       y = d.top() 

如果我運行這段代碼,該文件沒有保存。 另外,如果我刪除date.now(),只是把num_detected,它是正確保存 我不知道什麼是錯的文件名(因爲它的類型是strstr s的正確保存。

另外,如果我做

print(type(now),now) 

enter image description here 看來

我需要幫助。

+0

文件名謝謝你編輯的內​​容!我不知道它是如何工作的... 我應該學習更多..對此感到抱歉 –

+1

您傳遞給'.format'方法的參數數量不正確/額外。字符串中的「{0}」代表傳遞給'format'的* first *參數,在你的情況下它是'date.now()'。而且你傳遞了三個參數,但只消耗2個('{0}','{1}')。 –

+0

我已更改了代碼並再次進行了編輯。 所以對於{0},它是'not_detected_posture' ,對於{1}它是'str(date.now())' ,我仍然不知道發生了什麼 –

回答

0

由於包含日期時間,問題可能與文件名中的':''.'有關。我不確定哪一個,因爲你可以有包含這些的文件名,你可以在python AFAIK中編寫這樣的文件名。所以,這可能是cv2特定的問題。

0

我會爲文件名使用更有限的一組字符,避免像空格,冒號,括號之類的東西。使用自定義日期時間格式以您想要的形式生成時間戳。

實施例:

from datetime import datetime 
from os import path 


BASE_DIR = './images/non_detected' 
PREFIX = 'non_detected' 
EXTENSION = 'jpg' 
file_name_format = "{:s}-{:d}-{:%Y%m%d_%H%M%S}.{:s}" 


date = datetime.now() 
not_detected_posture = 0 


file_name = file_name_format.format(PREFIX, not_detected_posture, date, EXTENSION) 

file_path = path.normpath(path.join(BASE_DIR, file_name)) 

# --------- 

print("File name = '%s'" % file_name) 
print("File path = '%s'" % file_path) 

輸出:

File name = 'non_detected-0-20170819_152459.jpg' 
File path = 'images/non_detected/non_detected-0-20170819_152459.jpg' 

簡單,明確的和便攜式的。


也許還有一個改進。如果您大致瞭解您將生成多少張圖像,則可以對數字進行零填充,以便文件名按順序排序。例如,如果你知道會有至多10000,那麼你可以做

file_name_format = "{:s}-{:04d}-{:%Y%m%d_%H%M%S}.{:s}" 

你得到像

File name = 'non_detected-0000-20170819_152459.jpg'