繁体   English   中英

如何使用Python和OpenCV从目录中读取图像?

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

我写了以下代码:

import os
import cv2
import random
from pathlib import Path

path = Path(__file__).parent
path = "../img_folder"
for f in path.iterdir():

    f = str(f)

    img=cv2.imread(f)

    im_height = img.shape[0]
    im_width = img.shape[1]

但是,当我运行此代码时,出现以下错误:

AttributeError:“ imoneheight = img.shape [0]”中的“ NoneType”对象没有属性“ shape”。

我想我无法访问图像,所以我写了print(img)print(type(omg))并返回None&。 img_folder是一个包含10张图像的文件夹。 当我打印f ,我得到:

../img_folder/.DS_Store

我不知道为什么包含.DS_Store ,因为img_folder仅包含图像。 我该如何解决? 我该怎么写? 为什么我不能访问图像?

您已经发布了至少三个有关使用“ PostPath”获取文件名的问题。 厉害。

更好的方法是使用glob.glob获取文件名的特定类型。

$ tree .
├── a.txt
├── feature.py
├── img01.jpg
├── img01.png
├── imgs
│   ├── img02.jpg
│   └── img02.png
├── tt01.py
├── tt02.py
└── utils.py

1 directory, 9 files

从当前目录:

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']

.DS_Store文件是一种隐藏文件,它是在您可能已使用Finder应用程序打开的各个目录中自动生成的(仅在Mac OS中)。 我想这是某种缓存文件,用于在Finder快速轻松地呈现目录结构。 我观察到,如果不使用Finder应用程序打开目录,则不会创建该目录。

为避免此类错误,您必须始终检查要读取的文件是否具有有效的扩展名。 可以通过以下方式完成:

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)

这是因为目录中有一个隐藏文件。 如果确定目录仅包含图像,则可以忽略隐藏的文件/文件夹,如下所示。

采用

for f in path.iterdir():
    if not f.startswith('.'):

      f = str(f)

      img=cv2.imread(f)

      im_height = img.shape[0]
      im_width = img.shape[1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM