jp4.py 11.2 KB
Newer Older
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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
__copyright__ = "Copyright 2018, Elphel, Inc."
__license__ = "GPL-3.0+"
__maintainer__ = "Oleg Dzhimiev"
__email__ = "oleg@elphel.com"

import numpy as np
#import imageio
import elphel_exif

from PIL import Image, ImageOps

'''
Python image manipulation libs:

   Lib        Reads image as  Exif  Image manipulations     Comment
 Pillow(PIL)       Image       +            +            likes np.uint8 arrays
 imageio        numpy.array    -            -            almost useless
 opencv         numpy.array    -            +

Recommendations:
'''

# clear from code
def get_exif(filename):
  exif = elphel_exif.Exif(filename)
  #   exif.f - filename
  #   exif.data - parsed (as dict) exif with parsed MakeNote
  #   exif.MakerNote - parsed as dict
  return exif

# clear from code
def naur(a):
    b0 = a[0]
    b0 = np.reshape(b0,(1,b0.shape[0]))
    b  = a[:-1]
    b  = np.concatenate((b0,b),axis=0)
    return b

# clear from code
def nabr(a):
    b0 = a[-1]
    b0 = np.reshape(b0,(1,b0.shape[0]))
    b  = a[1:]
    b  = np.concatenate((b,b0),axis=0)
    return b

# clear from code
def nalc(a):
    b0 = a[::,0]
    b0 = np.reshape(b0,(b0.shape[0],1))
    b  = a[::,:-1]
    b  = np.concatenate((b0,b),axis=1)
    return b

# clear from code
def narc(a):
    b0 = a[::,-1]
    b0 = np.reshape(b0,(b0.shape[0],1))
    b  = a[::,1:]
    b  = np.concatenate((b,b0),axis=1)
    return b


class JP4:

    def __init__(self,filename="test.jp4"):

        # open image using PIL
        #i = Image.open(filename)
        #self.px = i.load()
        #self.px = scipy.misc.imread(filename, flatten=False, mode='RGB')
        #self.h, self.w, self.chn  = self.px.shape

        self.exif = get_exif(filename)

        # not JP4 - no deblock
        self.need_deblocking = True if self.exif.MakerNote['COLOR_MODE']==5 else False
        self.need_demosaicing = True if self.need_deblocking else False

        #print(self.exif.color_mode)
        #print(self.exif.MakerNote['GAIN_R'])
        #print(self.exif.MakerNote['GAIN_G'])
        #print(self.exif.MakerNote['GAIN_B'])
        #print(self.exif.MakerNote['GAIN_GB'])

        if   self.exif.MakerNote['BAYER_MODE']==0:
          self.bayer = [["Gr","R"],["B","Gb"]]
        elif self.exif.MakerNote['BAYER_MODE']==1:
          self.bayer = [["R","Gr"],["Gb","B"]]
        elif self.exif.MakerNote['BAYER_MODE']==2:
          self.bayer = [["B","Gb"],["Gr","R"]]
        elif self.exif.MakerNote['BAYER_MODE']==3:
          self.bayer = [["Gb","B"],["R","Gr"]]

        # open image
        # TODO: do not open twice (the 1st opening was when reading exif)
        im = Image.open(filename)

        # TODO: handle orientation
        # imageio - takes care about orientation
        # PIL     - does not, which is fine - just need to change bayer mosaic

        # rotated 90 CW
        if   self.exif.data['Orientation']==6:
          # keep bayer
          pass
          # horizontal mirror then rotated 270 CW
        elif self.exif.data['Orientation']==5:
          # change bayer mosaic
          if self.bayer==[["Gr","R"],["B","Gb"]]:
            self.bayer = [["B","Gb"],["Gr","R"]]

          #im = ImageOps.mirror(im)
          #im = im.rotate(270)

        # TODO: change bayer due to flips here

        # 'L' is 8 bit mode
        #self.image = scipy.misc.imread(filename, flatten=False, mode='L')

        #im_arr  = imageio.imread(filename)

        #im = im.rotate(90)
        #im = ImageOps.mirror(im)
        #im_arr = im.getdata()
        im_arr = np.fromstring(im.tobytes(), dtype=np.uint8)
        im_arr = im_arr.reshape((im.size[1], im.size[0]))

        print(im_arr.shape)

        self.image = im_arr
        self.h, self.w = self.image.shape



    # in JP4 format the 16x16 block is arranged in 8x32,
    # where color channels are grouped in 8x8 (8x8Gr, 8x8R, 8x8B, 8x8Gb)
    # the 1st line of 8x32 blocks is the left half of the image
    # the 2nd line of 8x32 blocks is the right half
    def deblock(self):

        if not self.need_deblocking:
            return 0

        # tmp copy
        I = np.copy(self.image)
        W = self.w
        H = self.h
        bayer = self.bayer

        # 16x16 block
        block  = np.zeros((16,16))
        # 16xW
        stripe = np.zeros((16,W))

        I = np.reshape(I,(H>>4,16,W))

        for i in range(I.shape[0]):
            # stripe 16xW
            stripe = np.copy(I[i])
            for j in range(0,W,16):
                if j<W/2:
                    k = 0
                    l = 2*j
                else:
                    k = 8
                    l = int(2*(j-W/2))

                # gr r b gb
                block[0::2,0::2] = stripe[k:k+8,l+ 0:l+ 0+8]
                block[0::2,1::2] = stripe[k:k+8,l+ 8:l+ 8+8]
                block[1::2,0::2] = stripe[k:k+8,l+16:l+16+8]
                block[1::2,1::2] = stripe[k:k+8,l+24:l+24+8]

                I[i,0:16,j:j+16] = block

        I = np.reshape(I,(H,W))
        self.image = I


    # gamma encode, gamma correct
    # incorrect, do not use
    def apply_gamma(self):
        print("apply gamma")
        #I = np.copy(self.image.astype(np.int32))
        I = np.copy(self.image)
        gain_r  = self.exif.MakerNote['GAIN_R']
        gain_gr = self.exif.MakerNote['GAIN_G']
        gain_b  = self.exif.MakerNote['GAIN_B']
        gain_gb = self.exif.MakerNote['GAIN_GB']

        I[0::2,0::2] = I[0::2,0::2]**(1/gain_gr)
        I[0::2,1::2] = I[0::2,1::2]**(1/gain_r)
        I[1::2,0::2] = I[1::2,0::2]**(1/gain_b)
        I[1::2,1::2] = I[1::2,1::2]**(1/gain_gb)

        self.image = I

    # unapply gamma
    # incorrect, do not use
    def linearize(self):
        print("unapply gamma")
        I = np.copy(self.image.astype(np.float))
        gain_r  = self.exif.MakerNote['GAIN_R']
        gain_gr = self.exif.MakerNote['GAIN_G']
        gain_b  = self.exif.MakerNote['GAIN_B']
        gain_gb = self.exif.MakerNote['GAIN_GB']

        I[0::2,0::2] = I[0::2,0::2]**gain_gr
        I[0::2,1::2] = I[0::2,1::2]**gain_r
        I[1::2,0::2] = I[1::2,0::2]**gain_b
        I[1::2,1::2] = I[1::2,1::2]**gain_gb

        # OpenCV uses BGR format
        self.image = I


    # simple but incorrect, with 2x downsampling
    # from here: https://groups.google.com/forum/#!topic/pydc1394/KycTwjyBDV0
    def demosaic_simple_downsample(self):

        if not self.need_demosaicing:
          return 0

        # no need in clipping
        I = np.copy(self.image)
        R = I[0::2,1::2]
        G = I[1::2,1::2]/2 + I[0::2,0::2]/2
        B = I[1::2,0::2]

        # OpenCV uses BGR format
        I = np.dstack([B,G,R])
        self.image = I


    def demosaic_bilinear_slow_and_true(self):

        if not self.need_demosaicing:
          return 0

        bayer = self.bayer
        I = np.copy(self.image.astype(np.float))
        R = np.copy(I)
        G = np.copy(I)
        B = np.copy(I)

        h,w = I.shape

        for j in range(h):
          for i in range(w):

            jt = j+1 if j==0   else j-1
            jb = j-1 if j==h-1 else j+1
            il = i+1 if i==0   else i-1
            ir = i-1 if i==w-1 else i+1

            px_0 = I[j,i]
            px_t, px_b, px_l, px_r  = I[jt,i], I[jb,i], I[j,il], I[j,ir]
            px_tl,px_tr,px_bl,px_br = I[jt,il],I[jt,ir],I[jb,il],I[jb,ir]

            if (bayer[j%2][i%2]=="Gr"):
              R[j,i] = (px_l + px_r)/2
              G[j,i] = (4*px_0 + px_tl + px_tr + px_bl + px_br)/8
              B[j,i] = (px_t + px_b)/2
            elif (bayer[j%2][i%2]=="R"):
              R[j,i] = px_0
              G[j,i] = (px_t + px_b + px_l + px_r)/4
              B[j,i] = (px_tl + px_tr + px_bl + px_br)/4
            elif (bayer[j%2][i%2]=="B"):
              R[j,i] = (px_tl + px_tr + px_bl + px_br)/4
              G[j,i] = (px_t + px_b + px_l + px_r)/4
              B[j,i] = px_0
            elif (bayer[j%2][i%2]=="Gb"):
              R[j,i] = (px_t + px_b)/2
              G[j,i] = (4*px_0 + px_tl + px_tr + px_bl + px_br)/8
              B[j,i] = (px_l + px_r)/2

        # OpenCV uses BGR format
        I = np.dstack([B,G,R])
        self.image = I
        return I


    def demosaic_bilinear(self):

        if not self.need_demosaicing:
          return 0

        bayer = self.bayer

        # int16 is enough, int32 - native and faster? need to test
        I = np.copy(self.image.astype(np.int32))
        R = np.copy(I)
        G = np.copy(I)
        B = np.copy(I)

        # this depends on bayer
        p00 = I[0::2,0::2]
        p01 = I[0::2,1::2]
        p10 = I[1::2,0::2]
        p11 = I[1::2,1::2]

        if   bayer==[["Gr","R"],["B","Gb"]]:

          R[0::2,0::2] = (p01 + nalc(p01))/2
          G[0::2,0::2] = (4*p00 + p11 + naur(p11) + nalc(p11 + naur(p11)))/8
          B[0::2,0::2] = (p10 + naur(p10))/2

          R[0::2,1::2] = p01
          G[0::2,1::2] = (p00 + narc(p00) + p11 + naur(p11))/4
          B[0::2,1::2] = (p10 + naur(p10) + narc(p10 + naur(p10)))/4

          R[1::2,0::2] = (p01 + nabr(p01) + nalc(p01 + nabr(p01)))/4
          G[1::2,0::2] = (p11 + nalc(p11) + p00 + nabr(p00))/4
          B[1::2,0::2] = p10

          R[1::2,1::2] = (p01 + nabr(p01))/2
          G[1::2,1::2] = (4*p11 + p00 + nabr(p00) + narc(p00 + nabr(p00)))/8
          B[1::2,1::2] = (p10 + narc(p10))/2

        elif bayer==[["R","Gr"],["Gb","B"]]:

          R[0::2,0::2] = p00
          G[0::2,0::2] = (p01 + nalc(p01) + p10 + naur(p10))/4
          B[0::2,0::2] = (p11 + naur(p11) + nalc(p11 + naur(p11)))/4

          R[0::2,1::2] = (p00 + narc(p00))/2
          G[0::2,1::2] = (4*p01 + p10 + naur(p10) + narc(p10 + naur(p10)))/8
          B[0::2,1::2] = (p11 + naur(p11))/2

          R[1::2,0::2] = (p00 + nabr(p00))/2
          G[1::2,0::2] = (4*p10 + p01 + nabr(p01) + nalc(p01 + nabr(p01)))/8
          B[1::2,0::2] = (p11 + nalc(p11))/2

          R[1::2,1::2] = (p00 + nabr(p00) + narc(p00 + nabr(p00)))/4
          G[1::2,1::2] = (p01 + nabr(p01) + p10 + narc(p10))/4
          B[1::2,1::2] = p11

        elif bayer==[["B","Gb"],["Gr","R"]]:

          R[0::2,0::2] = (p11 + naur(p11) + nalc(p11 + naur(p11)))/4
          G[0::2,0::2] = (p10 + naur(p10) + p01 + nalc(p01))/4
          B[0::2,0::2] = p00

          R[0::2,1::2] = (p11 + naur(p11))/2
          G[0::2,1::2] = (4*p01 + p10 + naur(p10) + narc(p10 + naur(p10)))/8
          B[0::2,1::2] = (p00 + narc(p00))/2

          R[1::2,0::2] = (p11 + nalc(p11))/2
          G[1::2,0::2] = (4*p10 + p01 + nabr(p01) + nalc(p01 + nabr(p01)))/8
          B[1::2,0::2] = (p00 + nabr(p00))/2

          R[1::2,1::2] = p11
          G[1::2,1::2] = (p10 + narc(p10) + p01 + nabr(p01))/4
          B[1::2,1::2] = (p00 + nabr(p00) + narc(p00 + nabr(p00)))/4

        # OpenCV uses BGR format
        I = np.dstack([B,G,R])
        self.image = I
        return I

    def saturation(self):

      I = self.image.astype(np.int32)

      # use '2' for now
      s = 2

      r = I[:,:,2]
      g = I[:,:,1]
      b = I[:,:,0]

      Y =  0.299*r+0.5870*g+ 0.144*b
      Cb = 128+s*(-0.1687*r-0.3313*g+ 0.500*b)
      Cr = 128+s*(    0.5*r-0.4187*g-0.0813*b)

      Cb[Cb<0]=0
      Cb[Cb>255]=255
      Cr[Cr<0]=0
      Cr[Cr>255]=255

      r = Y + 1.402*(Cr-128)
      g = Y - 0.34414*(Cb-128)-0.71414*(Cr-128)
      b = Y + 1.772*(Cb-128)

      r[r<0]=0
      r[r>255]=255
      g[g<0]=0
      g[g>255]=255
      b[b<0]=0
      b[b>255]=255

      # OpenCV uses BGR format
      I = np.dstack([b,g,r])

      self.image = I
      return I