Home > Enterprise >  PIL throws FileNotFoundError: [Errno 2] No such file or directory
PIL throws FileNotFoundError: [Errno 2] No such file or directory

Time:09-08

I'm working on a code to split images 1600x1200 in 12 slices parts. So I create this code:

def openFile():
    openf= filedialog.askopenfilename(initialdir="C:\\2022\\Python program\\All images",
                                         title= "Select a File", filetypes=(("jpg files", ".jpg"),("all files","*.*")))
    infile = Image.open(openf)
    #openf = cv2.resize(openf, (1280, 960)) #resize of original image
    #cv2.imshow('Original Image',openf)

 
def Analysis():
    global file, basename, chopsize, img
    file = filedialog.askopenfilename(initialdir="C:\\2022\\Python program\\All images",
                                         title= "Select a File", filetypes=(("jpg files", ".jpg"),("all files","*.*")))
    
    
    basename = os.path.basename(file)
    #print(basename)   
    
    img = Image.open(basename)
    #img = Image.open(file)
    #img2 = ImageOps.grayscale(img)
    chopsize = 400
    
    width, height = img.size

    print(img.size)


    # Save Chops of original image
    for x0 in range(0, width, chopsize):
       for y0 in range(0, height, chopsize):
          box = (x0, y0,
                 x0 chopsize if x0 chopsize <  width else  width - 1,
                 y0 chopsize if y0 chopsize < height else height - 1)
          print('%s %s' % (basename, box))
          #img.crop(box).save('zchop.%s.xd.yd.jpg' % (infile.replace('.jpg',''), x0, y0))
          
          img.crop(box).save("C:/2022/Python program/Caoba2022/Caoba images/Segmentation/Caoba_segment_color/zchop.%s.xd.yd.jpg" % (basename.replace('.jpg',''), x0, y0))
    
#####################################################################################################################################
    
    
def Analysis_gray():
    global file, basename, img
    #file = filedialog.askopenfilename(initialdir="C:\\2022\\Python program\\UFAC_bamboo2022\\images_pretreatement",
                                        # title= "Select a File", filetypes=(("jpg files", ".jpg"),("all files","*.*")))
    img = ImageOps.grayscale(img)
    width, height = img.size

    print(img.size)


    # Save Chops of original image
    for x0 in range(0, width, chopsize):
       for y0 in range(0, height, chopsize):
          box = (x0, y0,
                 x0 chopsize if x0 chopsize <  width else  width - 1,
                 y0 chopsize if y0 chopsize < height else height - 1)
          print('%s %s' % (basename, box))
          #img.crop(box).save('zchop.%s.xd.yd.jpg' % (infile.replace('.jpg',''), x0, y0))
          
          img.crop(box).save("C:/2022/Python program/Caoba2022/Caoba images/Segmentation/Caoba_segment_gray/zchop.%s.xd.yd.jpg" % (basename.replace('.jpg',''), x0, y0)) 

After I run this I get this error when I select an image:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\jra02028\Anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\jra02028\Documents\Python Scripts\Crop_program_color_gray.py", line 192, in <lambda>
    analysis_menu.add_command(label = "Transform data", command=lambda:[Analysis(), Analysis_gray()], image=fiber_img, compound='left')
  File "C:\Users\jra02028\Documents\Python Scripts\Crop_program_color_gray.py", line 115, in Analysis
    img = Image.open(basename)
  File "C:\Users\jra02028\Anaconda3\lib\site-packages\PIL\Image.py", line 3092, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'CAO7.jpg'

I trying to understand the error but is not clear to me. the line 115 is img = Image.open(basename) so I'm assuming the problem is with the string call without ' ' quotes

Is that the problem, What is wrong? Any ideas?

CodePudding user response:

You literally don't need os.path.basename because it only returns the name of the file. Unless your image file is the in current working directory, it doesn't work no matter what you do. You can just use the file variable you have. For example: Image.open(file) because filedialog.askopenfilename() returns the path of the file you have chosen.

Error explanation:

Basically when you call Image.open(file), it tries to read the file using the file name. Now when you give the filename it will first search in the directory where the python file is executed, but if you want it to search in some other directory then you need the full path of the file. If its in another folder of your current working directory then simply do this as the filename: TheFolder/image.png. Note this somehow does not work when you use Visual Studio Code. If you are using visual studio code then you might have to try os.getcwd() to get the current working directory of your python project folder. However this is not necessary when you run from the command line.

  • Related