1+ # Code Sample for "Processing RAW Images in Python", Pavel Rojtberg, 2015
2+
3+ import libraw # for loading
4+ import numpy as np # for processing
5+
6+ proc = libraw .LibRaw () # create RAW processor
7+ proc .open_file ("file.dng" ) # open file
8+ proc .unpack () # extract mosaic from file
9+ mosaic = proc .imgdata .rawdata .raw_image
10+
11+ ## Listing 1: Mapping to Linear Values
12+ linear = range (2 ** 16 ) # a linear LUT
13+ lin_lut = proc .imgdata .color .curve # linearization LUT
14+
15+ if any (lin_lut != linear ):
16+ mosaic = lin_lut [mosaic ] # apply LUT
17+
18+ black = mosaic .min ()#proc.imgdata.color.black
19+ saturation = proc .imgdata .color .maximum
20+
21+ uint14_max = 2 ** 14 - 1
22+ mosaic -= black # black subtraction
23+ mosaic *= int (uint14_max / (saturation - black ))
24+ mosaic = np .clip (mosaic ,0 ,uint14_max ) # clip to range
25+
26+ ## Listing 2: White Balancing
27+ assert (proc .imgdata .idata .cdesc == b"RGBG" )
28+
29+ cam_mul = proc .imgdata .color .cam_mul # RGB multipliers
30+ cam_mul /= cam_mul [1 ] # scale green to 1
31+ mosaic [0 ::2 , 0 ::2 ] *= cam_mul [0 ] # scale reds
32+ mosaic [1 ::2 , 1 ::2 ] *= cam_mul [2 ] # scale blues
33+ mosaic = np .clip (mosaic ,0 ,uint14_max )# clip to range
34+
35+ ## Listing 3: Demosaicing
36+ def demosaic (m ):
37+ r = m [0 ::2 , 0 ::2 ]
38+ g = np .clip (m [0 ::2 , 1 ::2 ]// 2 + m [1 ::2 , 0 ::2 ]// 2 ,
39+ 0 , 2 ** 16 - 1 )
40+ b = m [1 ::2 , 1 ::2 ]
41+ return np .dstack ([r , g , b ])
42+
43+ mosaic *= 2 ** 2 # expand to 16bit for demosaicing
44+ img = demosaic (mosaic ) # displayable rgb image
45+
46+ ## Listing 4: Color Space Conversion
47+ cam2srgb = proc .imgdata .color .rgb_cam [:, 0 :3 ]
48+ cam2srgb = np .round (cam2srgb * 255 ).astype (np .int16 )
49+ img = img // 2 ** 8 # reduce dynamic range to 8bpp
50+ shape = img .shape
51+ pixels = img .reshape (- 1 , 3 ).T # 3xN array of pixels
52+ pixels = cam2srgb .dot (pixels )// 255
53+ img = pixels .T .reshape (shape )
54+ img = np .clip (img , 0 , 255 ).astype (np .uint8 )
55+
56+ ## Listing 5: Gamma Correction
57+ gcurve = [(i / 255 ) ** (1 / 2.2 ) * 255 for i in range (256 )]
58+ gcurve = np .array (gcurve , dtype = np .uint8 )
59+
60+ img = gcurve [img ] # apply gamma LUT
61+
62+ ## show info and save output
63+ print ("libraw version:" , libraw .version ())
64+ print ("white balance multipliers" , cam_mul [:- 1 ])
65+ import matplotlib .image
66+ matplotlib .image .imsave ("out.png" , img )
0 commit comments