Skip to main content
Participant
October 17, 2020
Answered

Scripting - Get number of selected pixels?

  • October 17, 2020
  • 2 replies
  • 1366 views

Hi all,

 

Is it possible to access the number of selected pixels from the historam tab via script? If not is there another way to calcualte this?

 

This would be straight forward if the selection was rectangular however the selection is from the magic wand tool so an iregular shape.

 

Any help would be much appreciated.

Ved

This topic has been closed for replies.
Correct answer jazz-y

 

var a = 0, h = app.activeDocument.histogram;
for (i=0; i<256;i++) {a+= h[i]}
alert (a)

 

2 replies

JJMack
Community Expert
Community Expert
October 17, 2020

I used a sledge hammer on a script r-bin posted the get the histogram of a layer to get the canvas size or the selection selection size in pixels. using a temp empty layer. jazz-y script to total the array can do all as long as you target what you want the size of.

// R-bin You can turn off all other layers then get the histogram then turn on all layers again
// I added an empty layer so the last entry in the histogram will be the pixel count of the canvas or active selection
var TmpEmpty = app.activeDocument.artLayers.add();				
toggle_other_visible()
var hist = app.activeDocument.histogram;
//var hist = app.activeDocument.channels[0].histogram;
toggle_other_visible()
TmpEmpty.remove();
alert(hist[hist.length-1])

function toggle_other_visible() {
    try {
        var desc = new ActionDescriptor();
        var list = new ActionList();
        var ref = new ActionReference();
        ref.putEnumerated( charIDToTypeID( "Lyr " ), charIDToTypeID( "Ordn" ), charIDToTypeID( "Trgt" ) );
        list.putReference( ref );
        desc.putList( charIDToTypeID( "null" ), list );
        desc.putBoolean( charIDToTypeID( "TglO" ), true );
        executeAction( charIDToTypeID( "Shw " ), desc, DialogModes.NO );
        }
    catch (e) { alert(e);} 
}

 

 

JJMack
Legend
October 17, 2020

I hope r-bin has checked the time taken to create a new layer and toggle visibility 🙂

 

this option is also possible:

 

s2t = stringIDToTypeID;
(r = new ActionReference()).putProperty(s2t('property'), p = s2t('histogram'));
r.putEnumerated(s2t('document'), s2t('ordinal'), s2t('targetEnum'));
var h = executeActionGet(r).getList(p),
c = 0;
for (var i=0; i<256; i++) {c += h.getInteger(i)}
alert (c)

 

 

jazz-yCorrect answer
Legend
October 17, 2020

 

var a = 0, h = app.activeDocument.histogram;
for (i=0; i<256;i++) {a+= h[i]}
alert (a)