Sensors & Effectors/Camera

[OpenCV][Python] Save images periodically

jstar0525 2021. 7. 12. 16:08
반응형
import os
import cv2
from pathlib import Path
from datetime import datetime

path = Path('/home/ubuntu/data/')
path.mkdir(parents=True, exist_ok=True)
src = '/dev/video0'
interval = 0.3  # sec

def set_camera(src):
    cap = cv2.VideoCapture(src)
    cap.set(3, 1920)
    cap.set(4, 1080)

    return cap

def save_image(cap, interval, show_info=True):

    t1 = datetime(1000, 1, 1)

    while(True):
        t2 = datetime.now()
        dt = (t2-t1).total_seconds()

        if dt > interval:
            ret, frame = cap.read()

            t = t2.strftime('%Y-%m-%d_%H-%M-%S_%f')
            f_name = os.path.join(path, t)
            start = datetime.now()
            cv2.imwrite(f_name+'.png', frame)
            finish = datetime.now()
            
            if show_info:
                print('interval :', dt)
                print('file name:', t)
                print('save time:', (finish-start).total_seconds())

            t1 = t2

if __name__ == '__main__':
    cap = set_camera(src)
    save_image(cap, interval, show_info=True)
file name: 2021-07-12_19-24-41_861272
save time: 0.289047
interval : 0.300001
file name: 2021-07-12_19-24-42_161273
save time: 0.258691
interval : 0.300002
file name: 2021-07-12_19-24-42_461275
save time: 0.271431
interval : 0.300001
file name: 2021-07-12_19-24-42_761276
save time: 0.263211
interval : 0.300001
file name: 2021-07-12_19-24-43_061277
save time: 0.257437
interval : 0.300001
file name: 2021-07-12_19-24-43_361278
save time: 0.264336
interval : 0.300003
file name: 2021-07-12_19-24-43_661281
save time: 0.262699
interval : 0.300003
file name: 2021-07-12_19-24-43_961284
save time: 0.257417
interval : 0.300002
file name: 2021-07-12_19-24-44_261286
save time: 0.254599
interval : 0.300003
file name: 2021-07-12_19-24-44_561289
save time: 0.290181
interval : 0.300002
file name: 2021-07-12_19-24-44_861291
save time: 0.279567
interval : 0.300004
file name: 2021-07-12_19-24-45_161295
save time: 0.265829
interval : 0.300001
file name: 2021-07-12_19-24-45_461296
save time: 0.270736
interval : 0.300001
file name: 2021-07-12_19-24-45_761297
save time: 0.284527
interval : 0.300003
file name: 2021-07-12_19-24-46_061300
save time: 0.27595
interval : 0.300002
file name: 2021-07-12_19-24-46_361302
save time: 0.288619
interval : 0.300002
file name: 2021-07-12_19-24-46_661304
save time: 0.287218
interval : 0.300003
반응형