Search code examples
pythonerror-handlingpython-imaging-librarybounding-box

syntax error- cropping image using bounding box coordinates


I want to achieve coordinates using the last four numbers (which represent center and dimensions of bounding box) and crop the bounding box from the image with the same name (.jpg format).

I have written the following code:

import os
from PIL import Image
from os import listdir

directory = "/home/masoud/masoud/crop/obj"

for file in os.listdir(directory): 
    if file.endswith(".txt"):
        with open(os.path.join(directory, file), 'r') as f:
        
            for line in f:  # changed to file handle
                line = line.rstrip() # remove trailing '\n'
                nums = line.split()
                four_nums = nums[1:5]  
                # print(four_nums)
        image_name = os.path.splitext(os.path.join(directory, file)[0]+'.jpg'

        img = Image.open(os.path.join(directory, image_name))
                    width, height = img.size
        #             # Setting the points for cropped image 
                    left = width * (nums[1]- nums[3]/2)
                    top = height * (nums[2]- nums[4]/2)
                    right = width * (nums[1]+ nums[3]/2)
                    bottom = height * (nums[2]+ nums[4]/2)

        #             # Cropped image of above dimension 
        #             # (It will not change orginal image) 
                    im_cropped = img.crop((left, top, right, bottom)) 

                    im_cropped.show()
                    im_cropped.save('/home/masoud/masoud/crop/cropped-images', 'JPEG')

    else:
        continue

and txt files contents looks like below:

0 0.3547 0.5096 0.7293 1.0258

but I am getting the following syntax error.

File "/home/masoud/masoud/crop/crop.py", line 18
    img = Image.open(os.path.join(directory, image_name))
      ^
SyntaxError: invalid syntax
[Finished in 0.4s with exit code 1]
[cmd: ['/home/masoud/anaconda3/bin/python3', '-u', '/home/masoud/masoud/crop/crop.py']]
[dir: /home/masoud/masoud/crop]
[path: /home/masoud/bin:/home/masoud/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]

also directories look like this:

directories


Solution

  • You should use some IDE having a syntax check, like PyCharm CE, not the line 18, but line 17 is the problem: You are missing the closing bracket ")"

    image_name = os.path.splitext(os.path.join(directory, file)[0]+'.jpg'
    

    i assume you want:

    image_name = os.path.splitext(os.path.join(directory, file))[0]+'.jpg'