Lipstick - 7 months ago 15

Python Question

I try to use Moravec detection. When I try to run this code I get some error:

`diff = diff - image.getpixel((x, y))`

TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

How can I fix it? Any help will be appreciated. The code is:

`def moravec(image, threshold = 100):`

"""Moravec's corner detection for each pixel of the image."""

corners = []

xy_shifts = [(1, 0), (1, 1), (0, 1), (-1, 1)]

for y in range(1, image.size[1]-1):

for x in range(1, image.size[0]-1):

# Look for local maxima in min(E) above threshold:

E = 100000

for shift in xy_shifts:

diff = image.getpixel((x + shift[0], y + shift[1]))

diff = diff - image.getpixel((x, y))

diff = diff * diff

if diff < E:

E = diff

if E > threshold:

corners.append((x, y))

return corners

if __name__ == "__main__":

threshold = 100

image = Image.open('all.jpg')

corners = moravec(image, threshold)

draw_corners(image, corners)

image.save('low2.png')

Answer

You're trying to substract two tuples (with RGB values), and arithmetic operations on tuples like `*`

and `-`

are not defined.

To find the distance, you could just do this:

```
c1 = image.getpixel((x + shift[0], y + shift[1]))
c2 = image.getpixel((x, y))
diff = (c1[0] - c2[0]) ** 2 + (c1[1] - c2[1]) ** 2 + (c1[2] - c2[2]) ** 2
if diff < E:
E = diff
```

Hypothetically also could use `numpy`

to get the dot products and arithmetic operations working out of the box if that's what you're used to, although it's a bit of an overkill:

```
import numpy as np
c1 = image.getpixel((x + shift[0], y + shift[1]))
c2 = image.getpixel((x, y))
diff = (np.diff([c1, c2]) ** 2).sum()
if diff < E:
E = diff
```