为什么列表中的项目数量似乎错误

时间:2018-01-10 01:20:58

标签: python list opencv

我有以下Python脚本,我试图在列表中保存图像对:

import os
import os.path
import cv2
from collections import namedtuple

path = '/Users/abc/Desktop/images'
pairs = []

# initialization
img1 = None
img2 = None
Img = namedtuple('Img', ['data', 'name'])

for root, dirs, files in os.walk(path):
    for file in files:
        if file.startswith('1'):
            im1 = cv2.imread(root + '/' + '1.jpg')
            im1_file = '1.jpg'
            img1 = Img(im1,im1_file)
            print 'passed from here'
        elif file.startswith('2'):
            im2 = cv2.imread(root + '/' + '2.jpg')
            im2_file = '2.jpg'
            img2 = Img(im2,im2_file)
            print 'passed from here'

        pair = (img1,img2)
        pairs.append(pair)


[p for p in pairs if p is not (None,None)]

print len(p)

for img in p:
    print img.name

我有2个子目录,每个子目录有两个images 1.jpg2.jpg。上述脚本的输出是:

passed from here
passed from here
passed from here
passed from here
2
1.jpg
2.jpg

似乎循环遍历了两个子目录中的所有4个图像,但为什么我只得到1.jpg2.jpg而不是:

1.jpg
2.jpg
1.jpg
2.jpg

感谢。

3 个答案:

答案 0 :(得分:0)

因为p是最后一对。所以你想要:

for p in pairs:
    for img in p:
        print img.name

答案 1 :(得分:0)

我认为问题可能是你使用了错误的变量p

据我所见,您没有分配过滤后的结果。 [p for p in pairs if p is not (None,None)],此处p只是此列表理解中的中间变量。 p应该等于pairs中的最后一项。

你应该先保存它:

results = [p for p in pairs if p is not (None,None)]

print len(results)

答案 2 :(得分:0)

快速修复,供您参考。

path = '/Users/abc/Desktop/images'
pairs = []

# initialization
img1 = None
img2 = None
Img = namedtuple('Img', ['data', 'name'])

for root, dirs, files in os.walk(path):
    for file in files:
        if file.startswith('1'):
            im1 = cv2.imread(root + '/' + '1.jpg')
            im1_file = '1.jpg'
            img1 = Img(im1,im1_file)
            print 'passed from here'
        elif file.startswith('2'):
            im2 = cv2.imread(root + '/' + '2.jpg')
            im2_file = '2.jpg'
            img2 = Img(im2,im2_file)
            print 'passed from here'

    pair = (img1,img2) # unindent these two lines
    pairs.append(pair) # unindent these two lines

# you need save the result to a variable.
valid_pair = [p for p in pairs if p is not (None,None)]
# p is the last pair when you iterate the pairs list.
print len(p) # The pair is a tuple, has two elements, so length is 2.

for img in p: # p is a tuple, so you can iterate it successfully.
    print img.name  #print img1.name,print img2.name
# you need iterate the valid_pair!