How to read images from a directory with Python and OpenCV?

后端 未结 3 956
野趣味
野趣味 2021-01-24 17:08

I wrote the following code:

import os
import cv2
import random
from pathlib import Path

path = Path(__file__).parent
path = \"../img_folder\"
for f in path.iter         


        
3条回答
  •  -上瘾入骨i
    2021-01-24 17:32

    You have post at least three questions about get filenames with "PostPath". Badly.

    A better way is use glob.glob to get the specific type of filenames.

    $ tree .
    ├── a.txt
    ├── feature.py
    ├── img01.jpg
    ├── img01.png
    ├── imgs
    │   ├── img02.jpg
    │   └── img02.png
    ├── tt01.py
    ├── tt02.py
    └── utils.py
    
    1 directory, 9 files
    

    From current directory:

    import glob
    import itertools
    
    def getFilenames(exts):
        fnames = [glob.glob(ext) for ext in exts]
        fnames = list(itertools.chain.from_iterable(fnames))
        return fnames
    
    
    ## get `.py` and `.txt` in current folder
    exts = ["*.py","*.txt"]
    res = getFilenames(exts)
    print(res)
    # ['utils.py', 'tt02.py', 'feature.py', 'tt01.py', 'a.txt']
    
    
    # get `.png` in  current folder and subfolders
    exts = ["*.png","*/*.png"]
    res = getFilenames(exts)
    print(res)
    # ['img01.png', 'imgs/img02.png']
    

提交回复
热议问题