Вопрос

i trying to do subtraction. so here my command in python:

import math
cen = find_centroid(im, 1)
diff = cen-320
print diff

but error come out like this:

Traceback (most recent call last):
File "test7.py", line 26, in <module>
diff = cen-320
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

anyone please help me.

Это было полезно?

Решение

According to the error message, find_centroid returns a tuple.

Change subtraction expression accordingly:

cen[0] - 320

Or change the function to return a number instead of a tuple.

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

The issue is exactly what it says it is. You are trying to subtract an integer from a tuple. From looking at the code, cen must be the tuple because 320 is an integer. This means that find_centriod returns a tuple. This makes sense because a centroid will contain an x and a y coordinate.

If you only want the x coordinate, you can use cen[0]. If you only want the y coordinate, you can use cen[1].

The error message tells you all you need to know:

The result of find_centroids is a tuple - in Python those are written as (a,b,)

You can't subtract a number from a tuple. But you could do

diff = [x - 320 for x in cen]

This is called a "list comprehension". It says "evaluate x - 320 for every value of x that you find in cen, and return the values as a list in diff

Example:

>>> cen = (456,234,)
>>> diff = [x - 320 for x in cen]
>>> diff
[136, -86]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top