【问题标题】:syntax error- cropping image using bounding box coordinates使用边界框坐标的语法错误裁剪图像
【发布时间】:2020-10-28 02:50:54
【问题描述】:

我想使用最后四个数字(代表边界框的中心和尺寸)获得坐标,并从具有相同名称(.jpg 格式)的图像中裁剪边界框。

我写了以下代码:

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

txt 文件内容如下:

0 0.3547 0.5096 0.7293 1.0258

但我收到以下语法错误。

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]

目录也是这样的:

directories

【问题讨论】:

  • @HolgT 我使用 Sublime,但它没有突出显示没有括号。作为初学者,你认为 Pycharm 会是一个更好的选择吗?

标签: python error-handling python-imaging-library bounding-box


【解决方案1】:

您应该使用一些具有语法检查功能的 IDE,例如 PyCharm CE, 不是第 18 行,而是第 17 行的问题: 您缺少右括号“)”

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

我假设你想要:

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

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2020-04-26
    • 1970-01-01
    • 2021-06-03
    • 2021-09-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    相关资源
    最近更新 更多