简体   繁体   中英

Python - error reading file from list of filenames

I am trying to compare the first image in a folder to all other images in the same folder, to check for identical images. Simple idea - load the filenames of the folder in question to a list f, make a nested for loop to compare f[0] to f[1], f[2]...and so on. This works for f[0], f[1], f[2], but then gives IOError No such file or directory: '1_slice_0003.tif'. The file is in the folder, and it is written to f correctly (I can print f[3] without error). Length of f also matches the number of files in the image directory. What am I missing here?

from PIL import Image
import math, operator
import os

f = os.listdir("E:/JAWS/Converted_tiff/1")
count = 0

for filename in f:


    h1 = Image.open(filename).histogram()

    for filename in f:

       filename = f[count]
       h2 = Image.open(filename).histogram()

       rms = math.sqrt(reduce(operator.add,
                    map(lambda a,b: (a-b)**2, h1, h2))/len(h1))

       print str(f[count])
       print rms
       count += 1

You need to give path to folder as well.

for filename in f:
    h1 = Image.open(os.path.join(f, filename)).histogram()

You increase the count on the wrong level and you do not use the real path to open the file.

from PIL import Image
import math, operator
import os

f = os.listdir("E:/JAWS/Converted_tiff/1")
count = 0

for filename in f:


    h1 = Image.open(os.path.join(f, filename)).histogram()

    for filename in f:

       filename = f[count]
       h2 = Image.open(os.path.join(f, filename)).histogram()

       rms = math.sqrt(reduce(operator.add,
                    map(lambda a,b: (a-b)**2, h1, h2))/len(h1))

       print str(f[count])
       print rms

    count += 1

Btw, Instead opening file every time you can cache histograms for avoiding open same file over and over again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM