I am writing an image processing algorithm. The algorithm calculates a random contrast adjustment, and a random brightness adjustment, and applies those to each pixel in an image, like...
resultPixel = originalPixel * contrast + brightness
The problem is that the ranges for brightness and contrast are very large. Let's assume they are arbitrarily large and that it is necessary for them to be so. This means that a large number of my result images are completely white or completely black.
I don't want images which are completely white or completely black! But I am unsure exactly how to limit these values. Assuming...
pixelMax * contrast + brightness <= 255
and...
pixelMin * contrast + brightness >= 0
where pixelMax and pixelMin are constants
how can I get a random brightness and a random contrast value such that the above statements are true? I want all possible solutions to have an equal chance of being selected.
bonus: assume there are two contrast values, such that total contrast = contrast1 * contrast2
You can just solve as if it were a normal two-variable systems of equations. To do so, I used substitution:
Solving for contrast in terms of brightness and pixelMax in the first equation gives: $pixelMax * contrast <= 255 - brightness$
$contrast <= \frac{255-brightness}{pixelMax}$ (assuming $pixelMax>0$)
Solving for contrast in terms of brightness and pixelMin in the second equation gives: $pixelMin * contrast >= -brightness$
$contrast >= \frac{-brightness}{pixelMin}$ (assuming $pixelMin>0$)
Writing as a single equation gives $\boxed{\frac{-brightness}{pixelMin} <= contrast <= \frac{255 - brightness}{pixelMax}}$.
As I do not know the exact constants $pixelMin$ and $pixelMax$, I can only say pick a $brightness$ such that $\frac{-brightness}{pixelMin} <= \frac{255 - brightness}{pixelMax}$, and then pick a $contrast$ between the two.