如何使用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]
但是当我运行此代码时,出现以下错误:
But when I run this code, I get the following error:
AttributeError:"noneType"对象在im_height = img.shape [0]中没有属性"shape".
AttributeError: 'NoneType' object has no attribute 'shape' in im_height = img.shape[0].
我认为我无法访问图像,所以我写了print(img)
和print(type(omg))
以及None&返回. img_folder
是一个包含10张图像的文件夹.当我打印出f
时,我得到:
I think I cannot access images, so I wrote print(img)
and print(type(omg))
and None& is returned. img_folder
is a folder that has 10 images. When I print out f
, I get:
../img_folder/.DS_Store
../img_folder/.DS_Store
我不知道为什么包含.DS_Store
,因为img_folder
仅包含图像.我该如何解决?我该怎么写?为什么我不能访问图像?
I do not know why .DS_Store
is contained because img_folder
has only images. How should I fix this? What should I write this? Why can't I access images?
推荐答案
您至少发布了三个有关使用"PostPath"获取文件名的问题.不好.
You have post at least three questions about get filenames with "PostPath". Badly.
更好的方法是使用glob.glob
获取文件名的特定类型.
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
从当前目录:
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']
这篇关于如何使用Python和OpenCV从目录中读取图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!