# Image Gradient: Light to Dark, Dark to Light

Black-to-White transition is taken as Positive slope (it has a positive value) while White-to-Black transition is taken as a Negative slope (It has negative value). So when you convert data to np.uint8, all negative slopes are made zero. In simple words, you miss that edge.

So all i want is to write a function so i can keep negative gradient values. I know how to use Sobel.

Here is the sobel link where I got to know light-to-dark, dark-to-light are gradient directions, which are also referred as $+\text ve$ and $-\text ve$ directions.

IMPROVED Question: Please Suggest me a logic of the function to retain only $-\text ve$ values and clip $+\text ve$ values to zero?

My code:

Sobel(grayImg, grad, CV_16S, 0, 1, -1, BORDER_DEFAULT);
{
{
}
}


But i am not getting expected results. As per Sobel link, I want to get edge at black-to-white that is $+\text ve$ gradient and another one at white-to-black that is $-\text ve$ gradient

• Where is $-\text ve$ or $+\text ve$ in your link ? Commented Oct 20, 2015 at 20:09
• positive gradient and negative gradient are one and the same as light-to-dark and dark-to-light gradients. Commented Oct 21, 2015 at 11:07

The UINT8 type is limited to integer numbers on the range [0, 1, 2, ..., 255].
Hence negative values are clipped into 0.

A solution could be wither use other types (Floating Points) or scale and shift.

For instance, given a Floating Point image with values imageMax and imageMean you can scale it into the [0, 1, 2, ..., 255] by doing:

1. Create only positive numbers: image - imageMin.
2. Scale it into the range: round(255 * (image - imageMin) / (imageMax - imageMin)).

Now the conversion won't loose data.

Others have different approach, set 128 to be zero.
Namely, add 128 to the image, clip it into [0, 255] and then convert to UINT8.

Enjoy.

• I am aware of uint8 data type. I can use float to preserve values less than zero. What i want is only a logic, which stores negative values and clips positive values to 0. Commented Oct 21, 2015 at 11:11
• What do you mean? Logic of what?
– Royi
Commented Oct 21, 2015 at 16:57
• Please see my question once more. Commented Oct 28, 2015 at 11:42
• I still don't understand...
– Royi
Commented Oct 28, 2015 at 13:39
• @Mandar if you only want to store the negative values, then negate all the gradients before you convert the results to a uint8. Any values that are negative after negation should be set to zero. Commented Oct 29, 2015 at 10:29