Меню

Illegal target for annotation python ошибка

I have some simple if… elif… in my python3.6 (& OpenCV 4.0), but no matter what I do I keep getting strange error messages.

I need to crop some pics according to some bounding boxes.

# the image to be cropped loads here:
tobecropped= cv2.imread(img)
images.append(tobecropped)
(imageheight, imagewidth) = tobecropped.shape[:2]

# sample bounding box:
y = 833 # center vertically
x = 183 # center horizontally
width = 172
height = 103

# calculation of cropping values adding 10% extra:
y1 = y-(height/2*1.1)
y2 = y+(height/2*1.1)
x1 = x-(width/2*1.1)
x2 = x+(width/2*1.1)

# return values to int:
y1 = int(y1)
y2 = int(y2)
x1 = int(x1)
x2 = int(x2)

# move the cropping inside the original image:
If (y1 < 0): y_movedown()
Elif (y2 > imageheight): y_moveup()
Elif (x1 < 0) : x_moveright()
Elif (x2 > imagewidth): x_moveleft()

# actually cropping the image:
cropped = tobecropped[y1:y2, x1:x2]
cv2.imshow("cropped", cropped)

# functions to move the complete bounding box inside the image boundaries:
def y_movedown():
    y2=y2-y1
    y1=0
    print("moved down!")

def y_moveup():
    y1=y1-(y2-imageheight)
    y2=imageheight
    print("moved up!")

def x_moveright():
    x2=x2-x1
    x1=0
    print("moved right!")

def x_moveleft():
    x1=x1-(x2-imagewidth)
    x2=imagewidth
    print("moved left!")

the error message looks like this:

File "image_import2.py", line 121
   If (y1 < 0): y_movedown()
   ^
SyntaxError: illegal target for annotation

Does anyone see, what I am doing wrong here? Could not find any mention of such a mistake…

I was doing a Simple Calculator but it didnt work. Does anyone know why?

CalculatorTut = True
while CalculatorTut:
print(«1. Addition»)
print(«2. Subtraction»)
print(«multiplication»)
print(«4. Division»)
print(«5. Quit»)
cmd = int(input(«Enter Your Choice From 1 to 5»))

if cmd == 1:
print(«Addition»)
First = int (input(«Enter Second Number»))
Second = int (input(«Enter Second Number»))

Result = First + Second
print(First, ‘+’ , Second , ‘=’ , Result)

elif cmd == 2:
print(«Subtraction»)
First = int(input(«Enter First Number»))
Second = int (input(«Enter Second Number»))

Result = First — Second
print(First , ‘-‘ , Second , ‘=’ , Result)

elif cmd == 3:
print(«Multiplication»)
First = int(input(«Enter First Number»))
Second = int(input(«Enter Second number»))
Result = First * Second
print(First, ‘*’, Second, ‘=’, Result)

elif cmd == 4:
print(«Multiplication»)
First = int(input(«Enter First Number»))
Second = int(input(«Enter Second Number»))
Result = First / Second
print(First, ‘/’, Second, ‘/’, Result)

elif cmd == 5:
print(«Quit»)
CalculatorTut = False

Мне нужно обрезать несколько фотографий в соответствии с ограничивающими рамками.

# the image to be cropped loads here:
tobecropped= cv2.imread(img)
images.append(tobecropped)
(imageheight, imagewidth) = tobecropped.shape[:2]

# sample bounding box:
y = 833 # center vertically
x = 183 # center horizontally
width = 172
height = 103

# calculation of cropping values adding 10% extra:
y1 = y-(height/2*1.1)
y2 = y+(height/2*1.1)
x1 = x-(width/2*1.1)
x2 = x+(width/2*1.1)

# return values to int:
y1 = int(y1)
y2 = int(y2)
x1 = int(x1)
x2 = int(x2)

# move the cropping inside the original image:
If (y1 < 0): y_movedown()
Elif (y2 > imageheight): y_moveup()
Elif (x1 < 0) : x_moveright()
Elif (x2 > imagewidth): x_moveleft()

# actually cropping the image:
cropped = tobecropped[y1:y2, x1:x2]
cv2.imshow("cropped", cropped)

# functions to move the complete bounding box inside the image boundaries:
def y_movedown():
    y2=y2-y1
    y1=0
    print("moved down!")

def y_moveup():
    y1=y1-(y2-imageheight)
    y2=imageheight
    print("moved up!")

def x_moveright():
    x2=x2-x1
    x1=0
    print("moved right!")

def x_moveleft():
    x1=x1-(x2-imagewidth)
    x2=imagewidth
    print("moved left!")

Сообщение об ошибке выглядит так:

File "image_import2.py", line 121
   If (y1 < 0): y_movedown()
   ^
SyntaxError: illegal target for annotation

Кто-нибудь видит, что я здесь делаю не так? Не нашел упоминания о такой ошибке …

14 Задание: Типы данных и структуры данных Python для DevOps

Python PyPDF2 - запись метаданных PDF

Переменные, типы данных и операторы в Python

Почему Python - идеальный выбор для проекта AI и ML

Как автоматически добавлять котировки в заголовки запросов с помощью PyCharm

Анализ продукта магазина на Tokopedia

Анализ продукта магазина на Tokopedia

Tokopedia — это место, где продавцы могут продавать свои товары. Товар должен быть размещен на витрине, чтобы покупателям было легче найти товар…


Ответы
1

Ответ принят как подходящий

Взгляните на эти строки:

If (y1 < 0): y_movedown()
Elif (y2 > imageheight): y_moveup()
Elif (x1 < 0) : x_moveright()
Elif (x2 > imagewidth): x_moveleft()

If, Elif — это титульные слова, когда они должны быть в нижнем регистре, так что сделайте:

if (y1 < 0): y_movedown()
elif (y2 > imageheight): y_moveup()
elif (x1 < 0) : x_moveright()
elif (x2 > imagewidth): x_moveleft()

Вместо.

@powderscotty Пожалуйста, примите и проголосуйте, если это сработает, спасибо, рад помочь :-),


— U12-Forward

12.12.2018 02:00

Более общий ответ заключается в том, что у вас есть «:» в конце строки, в то время как строка не начинается с «if», «elif», «else», «for» и т. д.


— Zezombye

15.06.2021 16:31

Другие вопросы по теме

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Illegal opcode hp proliant ошибка
  • Illegal new face 3d max ошибка