Skip to main content
Participant
October 28, 2013
Question

Assessing the "Lightness" of a selected region?

  • October 28, 2013
  • 2 replies
  • 550 views

I am applying a logo to multiple pictures, and if the background for the location of the logo is dark, I want to use white text for the logo, but if the background for the location of the logo is light, I would like to use black text for the logo.

I'm already using a script to add the logo to the picture as a layer, so ideally I'd like to have some additional scripting text that would

  • select the region of the background where the logo will go (the regioin dimensions of which I know), and then
  • make a "Lightness" or "Darkness" assessment of the selected region

I'm guessing this might be relatively trivial to a more experienced scripter, but I'm still a newbie, and hence I don't have a clue.

Thanks in advance!

     Brian

This topic has been closed for replies.

2 replies

Inspiring
October 29, 2013

Hey,

You can use the mean value from the histogram for this. The below is taken from other posts on here and is something I use a lot. If the mean is "255" it is white. If it is "0" it is black ect.

var docRef = activeDocument;

var histo = docRef.histogram;

var mean = 0;

var total = 0;

for (var n = 0; n < histo.length; n++) {

total = total + histo;

};

for (var m = 0; m < histo.length; m++) {

var thisValue = histo;

mean = mean + (m * thisValue / total);

};

Just make a selection in the script and run this after and it will give you the mean value of the area.

Chuck Uebele
Community Expert
Community Expert
October 29, 2013

That's cool, Mark.

Chuck Uebele
Community Expert
Community Expert
October 28, 2013

I think a lot of this you can do by using scriptListner.  I would:

Stamp visible: shift-ctrl-alt-E to create a flat image of your layer, and reference it in your script so that you can return to it easily: var stampLayer = docRef.activeLayer

Place the logo where you want it, and reference that layer.

Either get the bounds of the logo layer and turn it into a selection: var layerBounds = docRef.activeLayer.bounds

or using SL ctrl/cmd-click on the logo layer icon to create a selection.

select your stamp layer and use filter>Blur>Average to get an even average of the logo area.

Set a color sampler in that area

Using the info from the sampler set up either a switch or a series of if statements to determine the color values in which you want the light or dark logo. 

Delete the stamp layer and possibliy your logo layer if it isn't the right one and replace the correct one.