NYCJUG/2010-03-09/ImproveContrast

From J Wiki
Jump to navigation Jump to search

Here's some code from Oleg that helps improve the contrast of text in a grayscale image.

Here's File:RemoveBackground.ijs:

deBackgroundImage=: 3 : 0
   M=. 16bff (17 b.) readimg y
   M2=. M{.~10*>:>.10%~$M          NB. Pad so dimensions divisible by 10+extra
   S=. |: _10(>./)\|: _10(>./)\M2  NB. Apply max filter to remove features
   Z=. 10#"1]10#S                  NB. Restore size to match original
   W=. |:8 (+/%#)\|:8 (+/%#)\ Z    NB. smooth with moving average-extra
   ($M){.W-~M2{.~$W                NB. remove shadows
NB.EG newimg=. deBackgroundImage 'ImagEG0.jpg'
NB.EG (|:3#,:|:sc00FF newimg) write_image 'ImagEG1.jpg'
)

We use these utilities to help write the resulting image using the "images" addon:

NB.* sc00FF: scale numbers 0-255 (for image).
sc00FF=: [: <. 0.5 + 0 255 scaleNums ]
NB.* scaleNums: general scaling of y to be >:0{x and <:1{x.
scaleNums=: 3 : 0
   0 1 scaleNums y
:
   'low hi'=. ((<./),>./)x
   if. 0 *./ . = 11 o. ,y do.
       nums=. y-<./,y
       nums=. nums%>./,nums       NB. scale from 0 to 1
   else.
       nums=. y-<./10 o. ,y
       nums=. nums%>./10 o. ,nums NB. scale from 0 to 1 for complex
   end.
   nums=. low+nums*hi-low
)