amount of rectangle intersection

I want to calculate how much a rectangle intersects another rectangle (normalized values).

I found this on stackoverflow:

Compute the area of the intersection, which is a rectangle too:

SI = Max(0, Max(XA2, XB2) - Min(XA1, XB1)) * Max(0, Max(YA2, YB2) - Min(YA1, YB1)) From there you compute the area of the union:

SU = SA + SB - SI And you can consider the ratio

SI / SU (100% in case of a perfect overlap, down to 0%).

http://stackoverflow.com/questions/9324339/how-much-do-two-rectangles-overlap

I tried to implement the first line but the values don't make sense. The more i move the mouse to the bottom right corner, the higher the values. Can someone take a look.

import java.awt.Rectangle;

Rectangle r1, r2;

void setup() {
  size(600, 600);

  r1 = new Rectangle(50, 50, 200, 200);
  r2 = new Rectangle(50, 50, 100, 100);
}

void draw() {
  background(0);

  rect(r1.x, r1.y, r1.width, r1.height);
  r2.x = mouseX;
  r2.y = mouseY;
  rect(r2.x, r2.y, r2.width, r2.height);

  println(interSectionAmount(r1, r2));
}

float interSectionAmount(Rectangle a, Rectangle b) {

  float si = max(0, max(a.x + a.width, b.x + b.width) - min(a.x, b.x)) * max(0, max(a.y + a.height, b.y + b.height) - min(a.y, b.y));

  return si;
}
Tagged:

Answers

  • edited April 2014 Answer ✓

    did you get anywhere with this or am i answering questions too late again? 8)

    this works:

    float interSectionAmount(Rectangle a, Rectangle b) {
    
      int top = max(a.y, b.y);
      int bottom = min(a.y + a.height, b.y + b.height);
      int left = max(a.x, b.x);
      int right = min(a.x + a.width, b.x + b.width);
      float si = max(0, right - left) * max(0, bottom - top);
    
      return si;
    }
    

    the number printed is the number of pixels in the overlap. when small square is wholly inside the big square it's 100x100, if it's outside it's 0.

    (i think your original problem may've just been the upside-down y-axis thing that processing does, but i ripped it all apart to get it working and i can't quite remember what i did to fix it!)

  • (um, i appear to have changed the two innermost min()s and max()s around. i swear it works though)

  • Thanks, and your never too late :)

    Below is the one that gives normalized values. For people that use it, the order doesn't matter:

    So this:

    println(interSectionAmount(r1, r2)); println(interSectionAmount(r2, r1));

    Will produce the same values.

    float interSectionAmount(Rectangle a, Rectangle b) {
    
      int top = max(a.y, b.y);
      int bottom = min(a.y + a.height, b.y + b.height);
      int left = max(a.x, b.x);
      int right = min(a.x + a.width, b.x + b.width);
      float si = max(0, right - left) * max(0, bottom - top);
    
      float su = (a.width * a.height) + (b.width * b.height) - si; 
    
      return si/su;
    }
    
Sign In or Register to comment.