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

后端 未结 3 954
野趣味
野趣味 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条回答
  •  不知归路
    2021-01-24 17:20

    The .DS_Store file is a kind of hidden file, which is automatically generated (only on Mac OS), inside the various directories, which you may have opened using the Finder application. I guess it is some sort of cache file for fast and easy rendering of directory structure in the Finder. I have observed that it doesn't gets created if I do not open the directory with my Finder application.

    To prevent this sort of errors, you must always check that the file you are going to read has a valid extension. It can be done as:

    import os
    
    for file_name in os.listdir("/path/to/your/directory"):
        if file_name.split(".")[-1].lower() in {"jpeg", "jpg", "png"}:
            img = cv2.imread("/path/to/your/directory/" + file_name)
    

提交回复
热议问题