python opencv读取图像序列,如何使用Python和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].

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

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值