# Otsu binarization with value preservation

I'm trying to implement a modified version of the otsu binarization algorithm. I'm trying to binarize document images. But in the binarization procedure I want the object (in this case the text) to retain its original grayscale value while the background takes the value of 255; that is, white. I'm posting a sample image version that I found in a paper.

This is the original image:

This is the resultant image I want to obtain:

Could someone please tell me how to do it in Matlab?

• You want to retain the giant gray blob? May 15 '12 at 19:20
• i want to retain the original values of all the pixels whose value lies above the threshold. That includes the blob in this case.
– mark
May 15 '12 at 19:52
• Matlab Source code for Otsu binarization with value preservation..
– user14952
Mar 6 '15 at 10:05

I don't have Matlab handy, but here is how you do it in OpenCV. The example below uses the python interface via Python (x, y):

test = cv2.imread("test.jpg", 0)
(_, otsu) = cv2.threshold(test, 0.0, 255.0, cv2.THRESH_TOZERO_INV + cv2.THRESH_OTSU)
cv2.imshow('otsu', otsu)


This results in your required output:

EDIT : I don't have a copy of Matlab, but I think this is how you would do it (assuming you have the Image Processing Toolbox):

Use graythresh to get the Otsu level, then set anything above that level to white (or 255).

I = imread('doc.jpg');
I = rgb2gray(I);
otsuLevel = graythresh(I);
I(I > otsuLevel) = 255;


Hope that helps!

• i need the code in matlab. I'm a little new to the software, so need a little help with the coding
– mark
May 16 '12 at 4:50
• @mark See my edit for a possible Matlab solution. May 16 '12 at 13:43

You can easily do it with Mathematica:

img = ColorNegate@ColorConvert[Import["../Desktop/sample.jpg"], "Grayscale"]
ColorNegate@ImageMultiply[Binarize[img], img]


The negation and multiplication business is to ensure the preservation of the original grayscale value. You can easily translate this to any language, I think.