2 Replies Latest reply on Dec 7, 2015 8:25 AM by cwodwrth

    Scripting: Count number of selected pixels (non-quadrangle) or alternative approach

    cwodwrth

      Is there a way to count the number of selected pixels in a selection that is not a quadrangle? For instance, if I cntl-click the thumbnail of some text layer, I'd like to know how many pixels are selected.

       

      Here is the application, if someone has an alternative approach to try....

       

      Untitled-1.jpg

       

      My goal is the place the text at some point where it not covering up any lines (or alternatively the spot where it covers up the fewest number of the line pixels). My approach is to insert some text in red at the desired location, apply a BlendMode.Multiply to the text. The number of red pixels still on the screen will show how many line pixels I'm covering up. Then I move the text across a region and check the histogram in index 76 (which is 255,0,0), find the point with the highest red count (meaning covering up the fewest line pixels) and finally move the text to that spot. See code snippet below:

       

      var bestCX = cX;

      var bestCY = cY;

      var bestPixelDensity = -1;

         

      var pixelDensity = 0;

      var searchRegionWidth = 3000;

      var searchRegionHeight = 2000;

       

      //loop across a region 3000x2000 around the desired location

      for(var x = cX - (searchRegionWidth/2); x < cX + (searchRegionWidth/2); x++)

      {

        for(var y = cY - (searchRegionHeight/2); y < cY + (searchRegionHeight/2); y++)

        {

          textItemRef.position = new Array(x, y);

          pixelDensity = myDocument.histogram[76]; //index of 255,0,0 (Red)

          //if this point is larger than the previous highest density, use this instead.

          if(pixelDensity > bestPixelDensity)

          {

            bestCX = x;

            bestCY = y;

            bestPixelDensity = pixelDensity;

          }

        }

      }

      //move text to the best location found

      textItemRef.position = new Array(bestCX, bestCY);

       

      The problem is that the images I'm using are very large ((7000x7000px)  so each check to the histogram takes a few seconds and I really need to move this across a pretty large region (3000x2000) to find the best spot. I figure it might be faster if I'm not using the histogram at all, and instead each time I move the text, I then select the text and see how many points are in the selection. Any help or alternative approaches would be great!