Loading...
Logo
Processing Forum
i am trying to build a visual instrument using JMyron0025 library ... i want to compare pixels globBoxes with predefined rectangle ... check for overlap condition n  change the color of the rectangle 

Replies(4)

The two functions below will do the job quickly.

In both cases the function parameters represent the top-left and bottom-right coordinates for the 2 rectangles. The first method returns true if the rectangles overlap. The second  method returns an array containing the top-left and bottom-right coordinates of any overlap region, if there is no overlap it returns an array of length zero.

Function 1
Copy code
  1. boolean box_box(float ax0, float ay0, float ax1, float ay1, float bx0, float by0, float bx1, float by1){
  2.     float topA = (float) Math.min(ay0, ay1);
  3.     float botA = (float) Math.max(ay0, ay1);
  4.     float leftA = (float) Math.min(ax0, ax1);
  5.     float rightA = (float) Math.max(ax0, ax1);
  6.     float topB = (float) Math.min(by0, by1);
  7.     float botB = (float) Math.max(by0, by1);
  8.     float leftB = (float) Math.min(bx0, bx1);
  9.     float rightB = (float) Math.max(bx0, bx1);
  10.     if(botA <= topB  || botB <= topA || rightA <= leftB || rightB <= leftA)
  11.         return false;
  12.     return true;   
  13. }
  14.    
  15. float[] box_box_p(float ax0, float ay0, float ax1, float ay1, float bx0, float by0, float bx1, float by1){
  16.     float[] result = new float[0];
  17.     float topA = (float) Math.min(ay0, ay1);
  18.     float botA = (float) Math.max(ay0, ay1);
  19.     float leftA = (float) Math.min(ax0, ax1);
  20.     float rightA = (float) Math.max(ax0, ax1);
  21.     float topB = (float) Math.min(by0, by1);
  22.     float botB = (float) Math.max(by0, by1);
  23.     float leftB = (float) Math.min(bx0, bx1);
  24.     float rightB = (float) Math.max(bx0, bx1);
  25.    
  26.     if(botA <= topB  || botB <= topA || rightA <= leftB || rightB <= leftA)
  27.         return result;
  28.     float leftO = (leftA < leftB) ? leftB : leftA;
  29.     float rightO = (rightA > rightB) ? rightB : rightA;
  30.     float botO = (botA > botB) ? botB : botA;
  31.     float topO = (topA < topB) ? topB : topA;
  32.     result =  new float[] {leftO, topO, rightO, botO};
  33.     return result;
  34. }





sir, code should be capable of detecting even single pixel overlap too;   
In both functions change the line
    if(botA <= topB  || botB <= topA || rightA <= leftB || rightB <= leftA)
to
    if(botA < topB  || botB < topA || rightA < leftB || rightB < leftA)

This will work if the parameters represent the actual top-left and bottom-right pixels.

You need to be careful when images are defined by the top-left pixel (x,y) , the width (w) and the height (h) of the image. In that case the bottom-right pixel position is gven by (x+w-1, y+h-1)