other_jk_colornorm.jl 11.4 KB
Newer Older
Jiri Borovec's avatar
Jiri Borovec committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
module colornorm
# Color normalization of microscopy images of Langerhans islets
# Jan Kybic, July 2015
#
# written in Julia



using Images
using ImageView
using Colors
using Debug

typealias ColorType{T} RGB{T}
typealias ColorImgType{T,N} Image{ColorType{T},N,Array{ColorType{T},N}}

function rgb2yuvimg{T}(img::ColorImgType{T,2})
    # convert an RGB image into YUV matrix
    imsize=size(img)
    r=zeros(Float32,(3,imsize[1],imsize[2]))
    for i=1:length(img) # process all pixels
        c=img[i]
        y=0.299*c.r+0.587*c.g+0.114*c.b # Y - luminosity
        r[1,i]=y
        r[2,i]=0.5+0.5*(c.b-y) # u between 0 and 1, not standard
        r[3,i]=0.5+0.5*(c.r-y) # v between 0 and 1
    end
    return r
end

function rgb2lbrimg{T}(img::ColorImgType{T,2})
    # convert an RGB image into luminosity and relative blue and red
    imsize=size(img)
    #r=zeros(Float32,(imsize[1],imsize[2]))
    r=zeros(Float32,(3,imsize[1],imsize[2]))
    for i=1:length(img) # process all pixels
        c=img[i]
        y=c.r+c.g+c.b # Y - luminosity
# J.Schier navrhuje:
#         r[1,i]=Float32(y)
#         r[2,i]=Float32(c.b)/y
#         r[3,i]=Float32(c.r)/y

        r[1,i]=y
        r[2,i]=c.b/y
        r[3,i]=c.r/y
    end
    return r
end



function yuv2rgb(yuv::Vector)
    b=2.*yuv[2]-1+yuv[1]
    r=2.*yuv[3]-1+yuv[1]
    g=(yuv[1]-0.299*r-0.114*b)/0.587
    return [r,g,b]
end    

function lbr2rgb(l::Vector)
    b=l[2]*l[1]
    r=l[3]*l[1]
    g=l[1]-b-r
    return [r,g,b]
end    


function rgb2lbr(x::Vector)
    l=x[1]+x[2]+x[3]
    b=x[3]/l
    r=x[1]/l
    return [l,b,r]
end

function rgb2yuv(rgb::Vector)
        y=0.299*rgb[1]+0.587*rgb[2]+0.114*rgb[3] # Y - luminosity
        u=0.5+0.5*(rgb[3]-y) # u between 0 and 1, not standard
        v=0.5+0.5*(rgb[1]-y) # v between 0 and 1
    return [y,u,v]
end
    
function percentile(vec::Vector,perc)
    # return a threshold value so that "perc" values in "vec" are smaller and 1-perc are larger
    @assert(perc>=0. && perc <=1. )
    sv=sort(vec)
    ind=min(round(Int,floor(length(vec)*perc))+1,length(vec))
    return sv[ind]
end

function hist2(m::Matrix,nbins)
    # create a 2D histogram from a (2,n) matrix, assume the values between 0 and 1 with nbins in each dimension
    n=size(m,2)
    @assert(size(m,1)==2)
    h=zeros(UInt32,nbins,nbins)
    nbinsf=float(nbins)
    for i=1:n
        iu=min(round(Int,floor(m[1,i]*nbinsf))+1,nbins)
        iv=min(round(Int,floor(m[2,i]*nbinsf))+1,nbins)
        h[iu,iv]+=1
    end
    return h
end

function hist2max(h::Matrix)
    # find the maximum element of the histogram and return the corresponding values
    nbins=size(h,1)
    rnbins=1./float(nbins)
    @assert(nbins==size(h,2))
    (iu,iv)=ind2sub(size(h),indmax(h))
    u=(iu-0.5)*rnbins
    v=(iv-0.5)*rnbins
    return (u,v)
end

function rgbimgmax{T}(img::ColorImgType{T,2})
    # return the maximum value in all channels of a RGB image
    return maximum(reshape(separate(img),size(img,1)*size(img,2),3),1).data'
end

function rgbimgpercentile{T}(img::ColorImgType{T,2};perc=0.01)
    # almost like rgbimg but ignore the highest 'perc' pixels (relative number)
    q=reshape(separate(img),size(img,1)*size(img,2),3).data
    return [percentile(q[:,1],1-perc), percentile(q[:,2],1-perc), percentile(q[:,3],1-perc)]
end
    
function piecewiselintransf(x0,y0,x)
    # calculates y=f(x), so that f(0)=0, f(1)=1, f(x0)=y0 and between these values the function is linear
    if x>x0
        return (x-x0)/(1-x0)*(1-y0)+y0
    else
        return x/x0*y0
    end
end

@debug function inventbluechannel{T}(img::ColorImgType{T,2};minval=0.2)
    # if the maximum blue channel value is smaller than minval, invent the blue value
    #maxrgb=rgbimgmax(img)
    maxrgb=rgbimgpercentile(img,perc=0.1)
    #println("maxrgb=$maxrgb")
    if maxrgb[3]<minval
        println("Inventing blue channel values")
        r=similar(img) # output image
        for i=1:length(img)
            r[i]=RGB(img[i].r,img[i].g,img[i].g)
        end
        return r
    end
    return img
end 

@debug function normalizeimg{T,N}(img::ColorImgType{T,N};topvals=0.1,nbins=100,method="max",corrmethod="ignoreoutliers",inventblue=true)
    # take an RGB image and change its colors so that the background is white
    # assume that most pixels in the image have the background pixels and that the "topvals" brightest pixels
    # belong to the background. "nbins" is the number of bins of a histogram
    # topvals is between 0 and 1.
    # method can be 'max' (most frequent color),
    #               'mean' (mean color in relative RGB space)
    #               'meanRGB'  (mean color in RGB space)
    # corrmethod can be 'norm',
    #                or 'hueonly'
    #                or 'limit'
    #                or 'clip'
    @assert(length(size(img))==2)
    if inventblue
        img=inventbluechannel(img)
    end
    r=similar(img) # output image
    lbr=rgb2lbrimg(img) # convert to luminosity and relative blue and red components
    # only consider topvals*length(img) brightest values
    lvec=reshape(lbr[1,:,:],length(img))
    threshold=percentile(lvec,topvals)
    inds=lvec.>threshold # indices to be considered
    br=reshape(lbr[2:3,:,:], 2,length(img)) 
    br=br[:,inds] # BR values of the brightest pixels
    if method=="max"
        h=hist2(br,nbins) # calculate histogram and find its maximum
        bb,br=hist2max(h) # coordinates of the maximum  = background color BR components
        brgb=lbr2rgb([1.,bb,br]) # background color in RGB
    elseif method=="mean" # use the mean
       bbr=mean(br,2)
       bb=bbr[1] ; br=bbr[2]
        brgb=lbr2rgb([1.,bb,br]) # background color in RGB
    elseif method=="meanRGB" # use the mean calculated in RGB
        rgbv=reshape(float32(separate(img).data),size(img,1)*size(img,2),3)
        brgb=mean(rgbv[inds,:],1)
    else
        error("Unknown method `$(method)'")
    end
    # now the bacground color is in brgb
    # calculate gain in RGB channels so that the background color "brgb" becomes white
    g=1./float(brgb) 
    if corrmethod=="norm"
         # adjust the gain so that the maximum value is one
         maxrgb=rgbimgmax(img)
         g*=1./maximum(maxrgb.*g)
         for i=1:length(img) # process all pixels
             r[i]=RGB(g[1]*img[i].r,g[2]*img[i].g,g[3]*img[i].b)
         end
    elseif corrmethod=="ignoreoutliers"
         # adjust the gain so that the maximum value is one except at very few places
         maxrgb=rgbimgpercentile(img,perc=0.01)
         g*=1./maximum(maxrgb.*g)
         for i=1:length(img) # process all pixels
             r[i]=RGB(min(g[1]*img[i].r,1.0),min(g[2]*img[i].g,1.0),min(g[3]*img[i].b,1.0))
         end
    elseif corrmethod=="hueonly"
         # adjust the gain so that the sum is one
         for i=1:length(img) # process all pixels
             y=img[i].r+img[i].g+img[i].b
             rn=g[1]*img[i].r ; gn=g[2]*img[i].g ; bn=g[3]*img[i].b ; 
             # scaling factor - keep intensity if possible but do not clip
             c=min(y/(rn+gn+bn),1./rn,1./gn,1./bn) 
             r[i]=RGB(c*rn,c*gn,c*bn)
         end
    elseif corrmethod=="hueonlyclip"
         # adjust the gain so that the sum is one
         for i=1:length(img) # process all pixels
             y=img[i].r+img[i].g+img[i].b
             rn=g[1]*img[i].r ; gn=g[2]*img[i].g ; bn=g[3]*img[i].b ; 
             # scaling factor - keep intensity if possible and clip if not possible
             c=y/(rn+gn+bn)
             r[i]=RGB(min(1.,c*rn),min(1.,c*gn),min(1.,c*bn))
         end

    elseif corrmethod=="clip"
         for i=1:length(img) # process all pixels
             r[i]=RGB(min(g[1]*img[i].r,1.0),min(g[2]*img[i].g,1.0),min(g[3]*img[i].b,1.0))
         end
     elseif corrmethod=="piecewise"
         t=sum(brgb)/3. # target gray
         for i=1:length(img) # process all pixels
             r[i]=RGB(piecewiselintransf(brgb[1],t,img[i].r),
                      piecewiselintransf(brgb[2],t,img[i].g),
                      piecewiselintransf(brgb[3],t,img[i].b))
         end
     else
         error("Unknown corrmethod `$(corrmethod)'")
     end
    
    return r
end


function test_normalizeimg()
    # try color normalization on one image
    a=imread(expanduser("~/work/IKEM/good_clinical/iz130305btxN1-10x.png"))
    b=normalizeimg(a,)
    ImageView.view(b)
end

function normalize_from_directory(inpdir, outdir)
    # normalize all images in a directory inpdir and save them to outpdir
    assert(isdir(inpdir))
    assert(isdir(outdir))
    files=readdir(inpdir)
    picture_extensions=Set([".png",".jpg",".bmp"])
    for filename in files
        fn,ext=splitext(filename)
        # process only image files
        if in(ext,picture_extensions)
            infilename=joinpath(inpdir,filename)
            outfilename=joinpath(outdir,filename)
            println("Processing file `$(infilename)' to `$(outfilename)'.")
            if isfile(outfilename) || isdir(outfilename)
                println("File exists, skipping.")
                continue
            end
            a=imread(infilename)
            println("Read")
            b=a
            try
                b=normalizeimg(a)
                println("Processed")
            catch
                println("Processing failed, reverting.")
            end
            imwrite(b,outfilename)
            println("Written")
        else
            println("Ignoring file `$(file)'.")
        end
    end
end

function test_colornorm()
    # normalize all images from a given directory
    # can be launched e.g. by import colornorm ; colornorm.test_colornorm()
    normalize_from_directory(expanduser("~/work/IKEM/good_clinical/"),expanduser("~/work/IKEM/good_clinical_colornorm"))
end

function normalize_training_set()
    normalize_from_directory("/mnt/tmp2/microscopy/IKEM/GT_IMAGE_TRENOVACI_SADA/images",expanduser("~/work/IKEM/images_colornorm"))
end

function normalize_all_clinical()
    normalize_from_directory("/mnt/tmp2/microscopy/IKEM/data20150730_all_clinical",expanduser("~/work/IKEM/data20150730_all_clinical_colornorm"))
end

function normalize_independent_donors()
    srcprefix="/mnt/tmp/microscopy/IKEM/Independent Donors2015"
    dstprefix="/mnt/tmp/microscopy/IKEM/Independent Donors2015_colornorm"
    for suffix in ["Donor7_iz150821d0","Donor8_iz150724d2","Donor9_iz150423d0"]
        normalize_from_directory(joinpath(srcprefix,suffix),joinpath(dstprefix,suffix))
    end
end

function normalize_independent_donors2()
    srcprefix="/mnt/tmp/microscopy/IKEM/Independent_Donors2015_2"
    dstprefix="/mnt/tmp/microscopy/IKEM/Independent_Donors2015_2_colornorm"
    normalize_from_directory(srcprefix,dstprefix)
end




function normalize_GT_IMAGE_PRO_BAREV_NORM()
    normalize_from_directory(expanduser("~/work/IKEM/GT_IMAGE_PRO_BAREV_NORM"),expanduser("~/work/IKEM/GT_IMAGE_PRO_BAREV_NORM_colornorm"))
end

function normalize_151015()
    normalize_from_directory("/mnt/tmp2/microscopy/IKEM/nova_izolace_15_10_15","/mnt/tmp2/microscopy/IKEM/nova_izolace_15_10_15_colornorm")
end

function normalize_241015()
    normalize_from_directory("/mnt/tmp2/microscopy/IKEM/nova_izolace_24_10_15","/mnt/tmp2/microscopy/IKEM/nova_izolace_24_10_15_colornorm")
end

function normalize_011115()
    normalize_from_directory("/mnt/tmp2/microscopy/IKEM/nova_izolace_1_11_15","/mnt/tmp2/microscopy/IKEM/nova_izolace_1_11_15_colornorm")
    normalize_from_directory("/mnt/tmp2/microscopy/IKEM/PURITY_1_11_2015","/mnt/tmp2/microscopy/IKEM/PURITY_1_11_2015_colornorm")
end


function normalize_thisdir()
    normalize_from_directory("inpimgs","outpimgs")
end

end