Ask Your Question
1

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

asked 2016-03-19 06:56:44 -0600

moresnow gravatar image

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[0],rect[1]), (rect[0]+rect[2],rect[1]+rect[3]), (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 flag offensive close merge delete

Comments

1

take a look at cv2.groupRectangles

sturkmen gravatar imagesturkmen ( 2016-03-19 10:29:49 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
2

answered 2016-03-20 07:23:19 -0600

berak gravatar image

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[0], b[0])
  y = min(a[1], b[1])
  w = max(a[0]+a[2], b[0]+b[2]) - x
  h = max(a[1]+a[3], b[1]+b[3]) - y
  return (x, y, w, h)

def intersection(a,b):
  x = max(a[0], b[0])
  y = max(a[1], b[1])
  w = min(a[0]+a[2], b[0]+b[2]) - x
  h = min(a[1]+a[3], b[1]+b[3]) - y
  if w<0 or h<0: return () # or (0,0,0,0) ?
  return (x, y, w, h)
edit flag offensive delete link more

Comments

1

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

moresnow gravatar imagemoresnow ( 2016-03-20 07:51:37 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2016-03-19 06:56:44 -0600

Seen: 30,371 times

Last updated: Mar 20 '16