Improving visual quality of a photo of a document

There is possibility that you do not have scanner at the moment and you made a photo of a document with your camera. Here is a small program how you can improve the photo especially if there is nonuniform light and shadows. I found the key idea in the blog of ABBY company (of course, they use much more advanced method).

initial = 
  ImageAdjust@
   ColorConvert[
    Import["http://habrastorage.org/files/76b/906/3d8/\
76b9063d8b9f44aebbb0411f7e51e46c.jpg"], "Grayscale"];
image = ColorNegate@WienerFilter[initial, denoising];


We need to define five parameters:

denoising = 1;
enhancement = {4, 3};
smoothing = True;

scale = 30;
gamma = 3

The first three are not important, but the last two are used for local contrast adjustment:

idata1 = Developer`ToPackedArray@ImageData[initial];
idata2 = Developer`ToPackedArray@
   ImageData[MeanFilter[initial, scale]];

idata2 = If[Min[idata2] > 0, idata2, 
   Module[{min = Union[Join @@ idata2][[2]]}, 
    Map[Max[#, min] &, idata2, {2}]]];

The idea is to remove shadows by using local gamma-correction:

localContrast = 
  ColorNegate@WienerFilter[Image[(idata1/idata2)^gamma], denoising];

mask = If[smoothing, Erosion[Dilation[Binarize[localContrast], 2], 1],
    Binarize[localContrast]];

Then one can use the mask to subtract background by inpainting:

background = 
  Inpaint[ImageMultiply[image, ColorNegate@mask], mask , 
   Method -> "NavierStokes"];

backgroundSubtracted = 
  ImageSubtract[ImageMultiply[image, mask], 
   ImageMultiply[background, mask]];

result = ColorNegate@
   ImageMultiply[
    ImageMultiply[backgroundSubtracted, enhancement[[1]]], 
    ImageMultiply[localContrast, enhancement[[2]]]];

That is it.

Of course, you can delete large artefacts “by hands”.

largecomponents = 
  ImageMultiply[
   GaussianFilter[
    DeleteSmallComponents[Binarize[ColorNegate@result, 0.1], 3000], 
    10], 4];

ColorNegate@
 ImageMultiply[ColorNegate@result, ColorNegate@largecomponents]

8 Likes

Hi Grisha,

Good tip!!

Thanks.
By the way I posted I question about improving a pic, would you have any suggestion?

I will appreciate.

http://community.wolfram.com/groups/-/m/t/223724?p_p_auth=qniT6LXf

1 Like