python - 语法错误-使用边界框坐标裁剪图像

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

我想使用最后四个数字(代表边界框的中心和尺寸)获得坐标,并从具有相同名称(.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

最佳答案

您应该使用一些具有语法检查功能的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'

关于python - 语法错误-使用边界框坐标裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62782166/

相关文章:

python - 将 RGB 颜色转换为调色板中最接近的颜色(网络安全颜色)?

python - 如何使用 PIL 将矩形图像映射到四边形?

python - 检测 Python 中的按键输入

python - Fandjango 的神秘问题

python - 将字典列表转换为嵌套字典

python - 使用 pandas 日期时间索引进行列表理解

wordpress - 动态更改 CF7 状态

php - 如何在 PHP 中捕获 require() 或 include() 的错误?

php - MAMP 显示 php 错误但没有警告

python - 将PIL图像转换为pygame表面图像