【发布时间】:2017-11-07 23:25:42
【问题描述】:
所以基本上我试图遍历我的子目录和文件(图像),这样每个子目录都包含两个图像,一个以单词 first 开头,一个以单词 @ 开头987654322@.
我想做的是,在每个子目录中,我想将以first开头的图像分配给变量img1,以second开头的图像分配给img2。
这是我得到的:
path = '/my_path/'
for root, dirs, files in os.walk(path):
for file in files:
if file.startswith('first'):
img1 = numpy.asarray(Image.open(root + '/' + file))
if file.startswith('second'):
img2 = numpy.asarray(Image.open(root + '/' + file))
print 'Image 1 is:'
print img1
print 'Image 2 is:'
print img2
但是,当我运行上述代码时,我得到以下信息:
Image 1 is:
Traceback (most recent call last):
File "test.py", line 17, in <module>
print img1
NameError: name 'img1' is not defined
我做错了什么?
谢谢。
【问题讨论】:
-
如果没有以
first开头的文件名怎么办? -
我确保每个子目录中唯一的文件名以“first”或“second”开头。
-
您的文件是否以“first”或“second”开头,还是两种类型都可以?
-
也许所有的子目录都有一个
first文件,但是你开始搜索的目录呢? -
@Reti43 是的,我可以同时拥有两种类型
标签: python image numpy python-imaging-library pillow