1

I have this code:

import cv2
from matplotlib import pyplot as plt
import numpy as np
img = cv2.imread('forklift2.jpg')

A = cv2.rectangle(img, (180, 90), (352, 275), (255,0,0), 2)
B = cv2.rectangle(img, (100, 220), (300, 275), (155,122,100), 2)

cv2.imshow('Object detector', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

I need to detect the intersection beetween the 2 rectangle A & B like as swown in the picture:

enter image description here

So I need to have a boolean variable that should be true if the 2 rectangles have some common area. How can I do that?

user3925023
  • 667
  • 6
  • 25
  • There are a lot of cases to consider here. Can the two rectangles be completely disjoint? Can one of them lie completely inside another? Else, a simple logic, like `if (pt.x > x0_2) and (pt.x < x1_1) and (pt.y > y0_2) and (pt.y < y1_1)` would do the trick; with `xi_j` where `i` is the start and end co-ordinate index and `j` is the rectangle index (similarly for `yi_j`). – mahesh Jul 25 '18 at 12:53
  • Hi, thx, there's definetely lots of cases, my question is about possibility to use a library (or cv2 function) that does the trick – user3925023 Jul 25 '18 at 13:09
  • https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html – mingganz Jul 25 '18 at 13:26
  • Module pygame has Rect class which has a function clip(). See here: https://www.pygame.org/docs/ref/rect.html#pygame.Rect.clip – mahesh Jul 25 '18 at 13:41

1 Answers1

0

You can reference IOU implement as following:

def pre_IOU(Reframe, GTframe):
    """
       input is rect diagonal points 
    """
    x1 = Reframe[0]
    y1 = Reframe[1]
    width1 = Reframe[2] - Reframe[0]
    height1 = Reframe[3] - Reframe[1]

    x2 = GTframe[0]
    y2 = GTframe[1]
    width2 = GTframe[2]-GTframe[0]
    height2 = GTframe[3]-GTframe[1]

    endx = max(x1+width1,x2+width2)
    startx = min(x1,x2)
    width = width1+width2-(endx-startx)

    endy = max(y1+height1,y2+height2)
    starty = min(y1,y2)
    height = height1+height2-(endy-starty)

    if width <=0 or height <= 0:
        ratio = 0
        return 0
    else:
        Area = width*height # two box cross  
        Area1 = width1*height1
        Area2 = width2*height2
        ratio = Area*1./(Area1+Area2-Area)
        return Area
Charles Cao
  • 116
  • 4