使用opencv将图像保存在不同的文件夹中

Saving images in different folders using opencv

我一直在尝试将网络摄像头中的图像保存在不同的文件夹中,但它不起作用。我试图实现的是我试图从我的网络摄像头为每个文件夹保存 5 张图像,但它不起作用。有人可以帮忙吗?谢谢 P.S 这是我的代码

def createFolder(directory):
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
    except OSError:
        print ('Error: Creating directory. ' +  directory)

import os 
import cv2 
import time 

video_capture = cv2.VideoCapture(0)
counter = 0
while(video_capture.isOpened()):
    location = f'D:/DATA_SCIENCE/anand_fabrics/{counter}'
    ret, frame = video_capture.read()
    cv2.imwrite(os.path.join(location , f"frame{counter}.jpg"), frame)
    if counter % 5 == 0:
        createFolder(f'D:/DATA_SCIENCE/anand_fabrics/{counter}')
    counter = counter + 1 

你说你每 5 张图片切换文件夹,但你每张图片都更改路径:

while(video_capture.isOpened()):
    location = f'D:/DATA_SCIENCE/anand_fabrics/{counter}'
    ...
    counter = counter + 1 

所以基本上你是在尝试写入一个不存在的路径。

试试这个:

video_capture = cv2.VideoCapture(0)
counter = 0
while(video_capture.isOpened()):
    if counter % 5 == 0:
        location = f'D:/DATA_SCIENCE/anand_fabrics/{counter}'
        createFolder(loaction)
    ret, frame = video_capture.read()
    cv2.imwrite(os.path.join(location , f"frame{counter}.jpg"), frame)
    counter = counter + 1