compare exact selection areas, NOT the bounding boxes

67 Views Asked by At

Is there a way to detect the different sizes of 2 different selections with identical bounding rectangles?

Using app.activeDocument.selection.bounds will return the dimensions of a rectangle bounding the selection. The two selections below will return identical bounds (39px x 38px). How can I distinguish them programmatically?

selection comparison

1

There are 1 best solutions below

2
Ghoul Fool On

When your selection images have been converted to black and white bitmaps:

So the trick is to take a colour sample of each pixel. We're not really interested in the colour of the pixel, but where it's part of the selection or not. Black if it is, white if it's not.

Then it's a matter of looping over the whole image, counting as you go. In a 39x38 size pixel image, the script will take a few seconds. On something larger, much much longer.

Bitmap selections

// creates an image of text that looks like
// a punch number on the back of a SNES cart
// The number will be random between 9 and 25;

// Switch off any dialog boxes
displayDialogs = DialogModes.NO; // OFF

// call the source document
var srcDoc = app.activeDocument;

var imageW = 39; // Custom image width
var imageH = 38; // Custom image height
var count = 0;
var pixelCount = 0;
var imageArea = imageW * imageH;

delete_all_colour_samples(); //just to be safe!

alert("This may take a while!\nBe patient.")

for (var x = 0; x < imageW; x++)
{
  for (var y = 0; y < imageH; y++)
  {
    try
    {
      var pointSample = srcDoc.colorSamplers.add([x,y]);
      count += 1; 
    }
      catch(eek)
    {
      alert("eek!\n" + "x,y\n" + x + ", " + y);
    }

     // Obtain RGB values.
      var r = Math.round(pointSample.color.rgb.red,0);
      var g = Math.round(pointSample.color.rgb.green,0);
      var b = Math.round(pointSample.color.rgb.blue,0);
     
     {
      // if it's a selection pixel (black) count it!
      if (r == 0 && g == 0 && b ==0) pixelCount +=1;
     }

     if (count >9)
     {
      // Photoshop can only have 10 samples at any time
      delete_all_colour_samples();
      // reset teh counter
      count = 0;
    }
   }
}

var selectionArea = pixelCount;
alert("Selection is: " + selectionArea + "\n out of:" + imageArea);
// 1,111/1482
// 813 /1482

// Set Display Dialogs back to normal
displayDialogs = DialogModes.ALL; // NORMAL



// function DELETE ALL COLOUR SAMPLES()
// --------------------------------------------------------
function delete_all_colour_samples()
{
   // Kill all colour samples
   app.activeDocument.colorSamplers.removeAll();
}