[英]syntax error- cropping image using bounding box coordinates
我想使用最后四個數字(代表邊界框的中心和尺寸)來獲得坐標,並從具有相同名稱(.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]
目錄也如下所示:
您應該使用一些 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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.