简体   繁体   English

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

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

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.iterdir():

    f = str(f)

    img=cv2.imread(f)

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

But when I run this code, I get the following error: 但是,当我运行此代码时,出现以下错误:

AttributeError: 'NoneType' object has no attribute 'shape' in im_height = img.shape[0]. AttributeError:“ imoneheight = img.shape [0]”中的“ NoneType”对象没有属性“ shape”。

I think I cannot access images, so I wrote print(img) and print(type(omg)) and None& is returned. 我想我无法访问图像,所以我写了print(img)print(type(omg))并返回None&。 img_folder is a folder that has 10 images. img_folder是一个包含10张图像的文件夹。 When I print out f , I get: 当我打印f ,我得到:

../img_folder/.DS_Store ../img_folder/.DS_Store

I do not know why .DS_Store is contained because img_folder has only images. 我不知道为什么包含.DS_Store ,因为img_folder仅包含图像。 How should I fix this? 我该如何解决? What should I write this? 我该怎么写? Why can't I access images? 为什么我不能访问图像?

You have post at least three questions about get filenames with "PostPath". 您已经发布了至少三个有关使用“ PostPath”获取文件名的问题。 Badly. 厉害。

A better way is use glob.glob to get the specific type of filenames. 更好的方法是使用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

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

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. .DS_Store文件是一种隐藏文件,它是在您可能已使用Finder应用程序打开的各个目录中自动生成的(仅在Mac OS中)。 I guess it is some sort of cache file for fast and easy rendering of directory structure in the Finder . 我想这是某种缓存文件,用于在Finder快速轻松地呈现目录结构。 I have observed that it doesn't gets created if I do not open the directory with my Finder application. 我观察到,如果不使用Finder应用程序打开目录,则不会创建该目录。

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)

It is because of a hidden file in your directory. 这是因为目录中有一个隐藏文件。 If you are sure your directory contains only images, you can ignore hidden files/folders like below. 如果确定目录仅包含图像,则可以忽略隐藏的文件/文件夹,如下所示。

use 采用

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.

相关问题 如何使用 OpenCV 读取图像目录 - How to read in a directory of images with OpenCV 如何使用 OpenCV 和 numpy 从 Drive 目录读取和显示图像? - How to read and display images from a Drive directory using OpenCV and numpy? 从特定目录读取多个图像,使用 python 和 opencv 将它们保存在另一个目录中 - Read multiple images from specific directory, prepossessed and save them another directory using python and opencv 使用Python和OpenCV处理目录中的图像 - Processing Images from a directory using Python and OpenCV Python - Opencv 读取 qr 图像 - Python - Opencv to read qr images 无法从 D 驱动器 [OpenCV] [Python] 读取或写入图像 - Can't read or write images from D Drive [OpenCV] [Python] 如何在 Python 中使用 opencv 从文件夹中读取图像序列(im1、im2、...)? - How can I read a sequence of images (im1, im2, ...) from a folder using opencv in Python? OpenCV 和 Python Flask 如何从文件夹和 ZF7B44CFAFD5C62223D7BZA2E 中读取图像到网站? - How can OpenCV with Python Flask read images from folder and stream them to website? 无法从文件夹中读取 bmp 图像,OpenCV (python) - can't read bmp images from folder ,OpenCV (python) python可以实时从目录读取图像吗? - Can python read images from directory in real-time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM