遍历目录中的图像并为Python中的每个结果分配变量

时间:2016-03-02 19:03:33

标签: python image for-loop

所以我试图循环浏览一个目录中的一组图像,并且我希望将每个计算的输出保存为它自己的变量,在本例中为d1,d2和d3。出于某种原因,这只输出d3而不输出其他值。任何有关错误的帮助都将不胜感激!

filelist = ['IMG_1.jpg','IMG_2.jpg', 'IMG_3.jpg']

for imagefile in filelist:
     for i in range(1,4):
          t=Image.open(imagefile).convert('L')

arr = array(t) #Convert test image into an array
f = arr + c #Add the corrective factor to the array with the UBM
f[f > 150] = 0
value = np.sum(f) #Sum elements in array
con = np.count_nonzero(f) #Count number of nonzero elements

arraysDict = {}
arraysDict['d{0}'.format(i)] = value/con

print arraysDict

如果我这样做(下图),它会打印d1,d2和d3的每个值,但由于某种原因它们是相同的。

filelist = ['IMG_1604.jpg','IMG_1605.jpg', 'IMG_1606.jpg']

for imagefile in filelist:
    t=Image.open(imagefile).convert('L')   
    arr = array(t) #Convert test image into an array
    f = arr + c #Add the corrective factor to the array with the UBM
    f[f > 150] = 0 
    value = np.sum(f) #Sum elements in array
    con = np.count_nonzero(f) #Count number of nonzero elements

arraysDict = {}
for i in range(1,4):
    arraysDict['d{0}'.format(i)] = value/con

q = arraysDict.values()
print q

1 个答案:

答案 0 :(得分:2)

您每次在arraysDict = {}循环内初始化for。这将清除旧数据。只需初始化for循环外的arraysDict = {}

filelist = ['IMG_1.jpg','IMG_2.jpg', 'IMG_3.jpg']

arraysDict = {}
value = {}
con = {}
i = 1

for imagefile in filelist:
      t=Image.open(imagefile).convert('L')
      arr = array(t) #Convert test image into an array
      f = arr + c #Add the corrective factor to the array with the UBM
      f[f > 150] = 0
      value[i] = np.sum(f) #Sum elements in array
      con[i] = np.count_nonzero(f) #Count number of nonzero elements
      i += 1


arraysDict = {}
for i in range(1,4):
    arraysDict['d{0}'.format(i)] = value[i]/con[i]

q = arraysDict.values()
print q