# How to perform intersection or union operations on a rect in Python?

I saw a question that is solved by using &(intersection) on rectangles http://answers.opencv.org/question/67...

I am trying to do the same in python.

I draw the rectangles like this:

for rect in rects_new:
#print (str(type(rect))) #<class 'numpy.ndarray'>
#print (rect.area()) # gives error that 'numpy.ndarray' object has no attribute 'area'
cv2.rectangle(vis, (rect,rect), (rect+rect,rect+rect), (0, 255, 255), 2)


but the rectangles are overlapping. I would only like to keep the outermost rectangle. However, I don't know how to perform & intersect operations. I can't even call area() on it.

edit retag close merge delete

1

Sort by » oldest newest most voted

there is no Rect class in python, like it would be in c++. in python a plain 4-element tuple is used instead.

you will have to come up with your own functions for intersection or union, similar to:

def union(a,b):
x = min(a, b)
y = min(a, b)
w = max(a+a, b+b) - x
h = max(a+a, b+b) - y
return (x, y, w, h)

def intersection(a,b):
x = max(a, b)
y = max(a, b)
w = min(a+a, b+b) - x
h = min(a+a, b+b) - y
if w<0 or h<0: return () # or (0,0,0,0) ?
return (x, y, w, h)

more

1

Thank you for clarifying that. I was able to use the Non-Maximal Suppression technique mentioned here http://www.pyimagesearch.com/2014/11/...

Official site

GitHub

Wiki

Documentation