It will be about writing notes so that you will not forget it.
A program related to image acquisition and storage using a WEB camera. It ’s one of the answers that beginners managed to reach. Please understand that it is poor if the viewer sees it.
I would appreciate it if you could give me some advice.
environment Windows10(64bit) anacondanavigator python3(3.7.7) opencv(3.4.2)
cap_save.ipynb
import cv2
import sys
import os
from datetime import datetime
I want to use dates for directory creation and file names
I'm using ʻosanddatetime`.
cap_save.ipynb
#Specifying the storage directory and defining the data name
dir_path = 'Destination'
basename = 'file name'
cap_save.ipynb
cap = cv2.VideoCapture(0)
Since (0) is set to use the built-in PC camera
When a web camera (USB camera) is connected, it is recognized as (1).
cap_save.ipynb
os.makedirs(dir_path,exist_ok=True)
base_path = os.path.join(dir_path,basename)
datename = datetime.now().strftime('%m%d%H%M')
Create an image save destination in the save destination directory (location set in dir_path) with ʻos.makedirs.  If the save destination exists, it will go to the next without any problem.  Join paths with ʻos.path.join.
datetime is set because you want to add the acquisition time to the file name.
cap_save.ipynb
n = 0
while True:
    
    ret,frame = cap.read()
    cv2.imshow(basename,frame)
    key = cv2.waitKey(1) & 0xFF    
    if key == ord('o'):
        cv2.imwrite((base_path + datename +'_'+ str(n) + ".png "),frame)
        n += 1
    elif key == ord('q'):
        break
        
cap.release()
cv2.destroyAllWindows()
I want to add serial numbers to the shot images themselves, so set n = 0 first.
After that, if you press the keyboard "O", you can use cv2.imwrite ((base_path + datename +'_' + str (n) +" .png "), frame)
Saves the image in the specified folder.
I think there is a more stylish way to write
I use this format to make it easier for me to understand "where" and "what name".
I was able to take an image → save it without any problems.
I implemented it on raspberrypi (stretch) with thonny and it ran without any problem.
that's all.
Recommended Posts