1# Copyright 2018 The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Verifies exposure times on RAW images.""" 15 16 17import logging 18import math 19import os.path 20import matplotlib 21from matplotlib import pylab 22from mobly import test_runner 23import numpy as np 24 25import its_base_test 26import camera_properties_utils 27import capture_request_utils 28import image_processing_utils 29import its_session_utils 30 31_BAYER_COLORS = ('R', 'Gr', 'Gb', 'B') 32_BLK_LVL_RTOL = 0.1 33_BURST_LEN = 10 # break captures into burst of BURST_LEN requests 34_EXP_LONG_THRESH = 1E6 # 1ms 35_EXP_MULT_SHORT = pow(2, 1.0/3) # Test 3 steps per 2x exposure 36_EXP_MULT_LONG = pow(10, 1.0/3) # Test 3 steps per 10x exposure 37_IMG_DELTA_THRESH = 0.99 # Each shot must be > 0.99*previous 38_IMG_SAT_RTOL = 0.01 # 1% 39_IMG_STATS_GRID = 9 # find used to find the center 11.11% 40_NAME = os.path.splitext(os.path.basename(__file__))[0] 41_NS_TO_MS_FACTOR = 1.0E-6 42_NUM_ISO_STEPS = 5 43 44 45def create_test_exposure_list(e_min, e_max): 46 """Create the list of exposure values to test.""" 47 e_list = [] 48 mult = 1.0 49 while e_min*mult < e_max: 50 e_list.append(int(e_min*mult)) 51 if e_min*mult < _EXP_LONG_THRESH: 52 mult *= _EXP_MULT_SHORT 53 else: 54 mult *= _EXP_MULT_LONG 55 if e_list[-1] < e_max*_IMG_DELTA_THRESH: 56 e_list.append(int(e_max)) 57 return e_list 58 59 60def define_raw_stats_fmt(props): 61 """Define format with active array width and height.""" 62 aax = props['android.sensor.info.preCorrectionActiveArraySize']['left'] 63 aay = props['android.sensor.info.preCorrectionActiveArraySize']['top'] 64 aaw = props['android.sensor.info.preCorrectionActiveArraySize']['right']-aax 65 aah = props['android.sensor.info.preCorrectionActiveArraySize']['bottom']-aay 66 return {'format': 'rawStats', 67 'gridWidth': aaw // _IMG_STATS_GRID, 68 'gridHeight': aah // _IMG_STATS_GRID} 69 70 71def create_plot(exps, means, sens, log_path): 72 """Create plots R, Gr, Gb, B vs exposures. 73 74 Args: 75 exps: array of exposure times in ms 76 means: array of means for RAW captures 77 sens: int value for ISO gain 78 log_path: path to write plot file 79 Returns: 80 None 81 """ 82 # means[0] is black level value 83 r = [m[0] for m in means[1:]] 84 gr = [m[1] for m in means[1:]] 85 gb = [m[2] for m in means[1:]] 86 b = [m[3] for m in means[1:]] 87 pylab.figure(f'{_NAME}_{sens}') 88 pylab.plot(exps, r, 'r.-', label='R') 89 pylab.plot(exps, gr, 'g.-', label='Gr') 90 pylab.plot(exps, gb, 'k.-', label='Gb') 91 pylab.plot(exps, b, 'b.-', label='B') 92 pylab.xscale('log') 93 pylab.yscale('log') 94 pylab.title(f'{_NAME} ISO={sens}') 95 pylab.xlabel('Exposure time (ms)') 96 pylab.ylabel('Center patch pixel mean') 97 pylab.legend(loc='lower right', numpoints=1, fancybox=True) 98 matplotlib.pyplot.savefig( 99 f'{os.path.join(log_path, _NAME)}_s={sens}.png') 100 pylab.clf() 101 102 103def assert_increasing_means(means, exps, sens, black_levels, white_level): 104 """Assert that each image increases unless over/undersaturated. 105 106 Args: 107 means: BAYER COLORS means for set of images 108 exps: exposure times in ms 109 sens: ISO gain value 110 black_levels: BAYER COLORS black_level values 111 white_level: full scale value 112 Returns: 113 None 114 """ 115 lower_thresh = np.array(black_levels) * (1 + _BLK_LVL_RTOL) 116 logging.debug('Lower threshold for check: %s', lower_thresh) 117 allow_under_saturated = True 118 for i in range(1, len(means)): 119 prev_mean = means[i-1] 120 mean = means[i] 121 122 if math.isclose(max(mean), white_level, rel_tol=_IMG_SAT_RTOL): 123 logging.debug('Saturated: white_level %f, max_mean %f', 124 white_level, max(mean)) 125 break 126 127 if allow_under_saturated and min(mean-lower_thresh) < 0: 128 # All channel means are close to black level 129 continue 130 allow_under_saturated = False 131 # Check pixel means are increasing (with small tolerance) 132 logging.debug('iso: %d, exp: %.3f, means: %s', sens, exps[i-1], mean) 133 for ch, color in enumerate(_BAYER_COLORS): 134 if mean[ch] <= prev_mean[ch] * _IMG_DELTA_THRESH: 135 e_msg = (f'{color} not increasing with increased exp time! ' 136 f'ISO: {sens}, ') 137 if i == 1: 138 e_msg += f'black_level: {black_levels[ch]}, ' 139 else: 140 e_msg += (f'exp[i-1]: {exps[i-2]:.3f}ms, ' 141 f'mean[i-1]: {prev_mean[ch]:.2f}, ') 142 e_msg += (f'exp[i]: {exps[i-1]:.3f}ms, mean[i]: {mean[ch]}, ' 143 f'TOL: {_IMG_DELTA_THRESH}') 144 raise AssertionError(e_msg) 145 146 147class RawExposureTest(its_base_test.ItsBaseTest): 148 """Capture RAW images with increasing exp time and measure pixel values.""" 149 150 def test_raw_exposure(self): 151 logging.debug('Starting %s', _NAME) 152 with its_session_utils.ItsSession( 153 device_id=self.dut.serial, 154 camera_id=self.camera_id, 155 hidden_physical_id=self.hidden_physical_id) as cam: 156 props = cam.get_camera_properties() 157 props = cam.override_with_hidden_physical_camera_props(props) 158 camera_properties_utils.skip_unless( 159 camera_properties_utils.raw16(props) and 160 camera_properties_utils.manual_sensor(props) and 161 camera_properties_utils.per_frame_control(props) and 162 not camera_properties_utils.mono_camera(props)) 163 log_path = self.log_path 164 165 # Load chart for scene 166 its_session_utils.load_scene( 167 cam, props, self.scene, self.tablet, 168 its_session_utils.CHART_DISTANCE_NO_SCALING) 169 170 # Create list of exposures 171 e_min, e_max = props['android.sensor.info.exposureTimeRange'] 172 e_test = create_test_exposure_list(e_min, e_max) 173 e_test_ms = [e*_NS_TO_MS_FACTOR for e in e_test] 174 175 # Capture with rawStats to reduce capture times 176 fmt = define_raw_stats_fmt(props) 177 178 # Create sensitivity range from min to max analog sensitivity 179 sens_min, _ = props['android.sensor.info.sensitivityRange'] 180 sens_max = props['android.sensor.maxAnalogSensitivity'] 181 sens_step = (sens_max - sens_min) // _NUM_ISO_STEPS 182 white_level = float(props['android.sensor.info.whiteLevel']) 183 black_levels = [image_processing_utils.get_black_level( 184 i, props) for i, _ in enumerate(_BAYER_COLORS)] 185 186 # Do captures with exposure list over sensitivity range 187 for s in range(sens_min, sens_max, sens_step): 188 # Break caps into bursts and do captures 189 burst_len = _BURST_LEN 190 caps = [] 191 reqs = [capture_request_utils.manual_capture_request( 192 s, e, 0) for e in e_test] 193 # Eliminate burst len==1. Error because returns [[]], not [{}, ...] 194 while len(reqs) % burst_len == 1: 195 burst_len -= 1 196 # Break caps into bursts 197 for i in range(len(reqs) // burst_len): 198 caps += cam.do_capture(reqs[i*burst_len:(i+1)*burst_len], fmt) 199 last_n = len(reqs) % burst_len 200 if last_n: 201 caps += cam.do_capture(reqs[-last_n:], fmt) 202 203 # Extract means for each capture 204 means = [] 205 means.append(black_levels) 206 for i, cap in enumerate(caps): 207 mean_image, _ = image_processing_utils.unpack_rawstats_capture(cap) 208 mean = mean_image[_IMG_STATS_GRID // 2, _IMG_STATS_GRID // 2] 209 logging.debug('ISO=%d, exp_time=%.3fms, mean=%s', 210 s, (e_test[i] * _NS_TO_MS_FACTOR), str(mean)) 211 means.append(mean) 212 213 # Create plot 214 create_plot(e_test_ms, means, s, log_path) 215 216 # Each shot mean should be brighter (except under/overexposed scene) 217 assert_increasing_means(means, e_test_ms, s, black_levels, white_level) 218 219if __name__ == '__main__': 220 test_runner.main() 221