1# Copyright 2015 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 android.edge.mode param behavior for reprocessing reqs.""" 15 16 17import logging 18import os 19import math 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 30import opencv_processing_utils 31 32EDGE_MODES = {'OFF': 0, 'FAST': 1, 'HQ': 2, 'ZSL': 3} 33EDGE_MODES_VALUES = list(EDGE_MODES.values()) 34NAME = os.path.splitext(os.path.basename(__file__))[0] 35NUM_SAMPLES = 4 36PLOT_COLORS = {'yuv': 'r', 'private': 'g', 'none': 'b'} 37SHARPNESS_RTOL = 0.15 38 39 40def check_edge_modes(sharpness): 41 """Check that the sharpness for the different edge modes is correct.""" 42 logging.debug('Verify HQ is sharper than OFF') 43 if sharpness[EDGE_MODES['HQ']] < sharpness[EDGE_MODES['OFF']]: 44 raise AssertionError(f"HQ < OFF! HQ: {sharpness[EDGE_MODES['HQ']]:.5f}, " 45 f"OFF: {sharpness[EDGE_MODES['OFF']]:.5f}") 46 47 logging.debug('Verify ZSL is similar to OFF') 48 if not math.isclose(sharpness[EDGE_MODES['ZSL']], 49 sharpness[EDGE_MODES['OFF']], rel_tol=SHARPNESS_RTOL): 50 raise AssertionError(f"ZSL: {sharpness[EDGE_MODES['ZSL']]:.5f}, " 51 f"OFF: {sharpness[EDGE_MODES['OFF']]:.5f}, " 52 f'RTOL: {SHARPNESS_RTOL}') 53 54 logging.debug('Verify OFF is not sharper than FAST') 55 if (sharpness[EDGE_MODES['FAST']] <= 56 sharpness[EDGE_MODES['OFF']] * (1.0-SHARPNESS_RTOL)): 57 raise AssertionError(f"FAST: {sharpness[EDGE_MODES['FAST']]:.5f}, " 58 f"OFF: {sharpness[EDGE_MODES['OFF']]:.5f}, " 59 f'RTOL: {SHARPNESS_RTOL}') 60 61 logging.debug('Verify FAST is not sharper than HQ') 62 if (sharpness[EDGE_MODES['HQ']] <= 63 sharpness[EDGE_MODES['FAST']] * (1.0-SHARPNESS_RTOL)): 64 raise AssertionError(f"FAST: {sharpness[EDGE_MODES['FAST']]:.5f}, " 65 f"HQ: {sharpness[EDGE_MODES['HQ']]:.5f}, " 66 f'RTOL: {SHARPNESS_RTOL}') 67 68 69def do_capture_and_determine_sharpness( 70 cam, edge_mode, sensitivity, exp, fd, out_surface, chart, log_path, 71 reprocess_format=None): 72 """Return sharpness of the output images and the capture result metadata. 73 74 Processes a capture request with a given edge mode, sensitivity, exposure 75 time, focus distance, output surface parameter, and reprocess format 76 (None for a regular request.) 77 78 Args: 79 cam: An open device session. 80 edge_mode: Edge mode for the request as defined in android.edge.mode 81 sensitivity: Sensitivity for the request as defined in 82 android.sensor.sensitivity 83 exp: Exposure time for the request as defined in 84 android.sensor.exposureTime. 85 fd: Focus distance for the request as defined in 86 android.lens.focusDistance 87 out_surface: Specifications of the output image format and size. 88 chart: object containing chart information 89 log_path: location to save files 90 reprocess_format: (Optional) The reprocessing format. If not None, 91 reprocessing will be enabled. 92 93 Returns: 94 Object containing reported edge mode and the sharpness of the output 95 image, keyed by the following strings: 96 'edge_mode' 97 'sharpness' 98 """ 99 100 req = capture_request_utils.manual_capture_request(sensitivity, exp) 101 req['android.lens.focusDistance'] = fd 102 req['android.edge.mode'] = edge_mode 103 if reprocess_format: 104 req['android.reprocess.effectiveExposureFactor'] = 1.0 105 106 sharpness_list = [] 107 caps = cam.do_capture([req]*NUM_SAMPLES, [out_surface], reprocess_format) 108 for n in range(NUM_SAMPLES): 109 y, _, _ = image_processing_utils.convert_capture_to_planes(caps[n]) 110 chart.img = image_processing_utils.get_image_patch( 111 y, chart.xnorm, chart.ynorm, chart.wnorm, chart.hnorm) 112 if n == 0: 113 image_processing_utils.write_image( 114 chart.img, '%s_reprocess_fmt_%s_edge=%d.jpg' % ( 115 os.path.join(log_path, NAME), reprocess_format, edge_mode)) 116 edge_mode_res = caps[n]['metadata']['android.edge.mode'] 117 sharpness_list.append( 118 image_processing_utils.compute_image_sharpness(chart.img)*255) 119 logging.debug('Sharpness list for edge mode %d: %s', 120 edge_mode, str(sharpness_list)) 121 return {'edge_mode': edge_mode_res, 'sharpness': np.mean(sharpness_list)} 122 123 124class ReprocessEdgeEnhancementTest(its_base_test.ItsBaseTest): 125 """Test android.edge.mode param applied when set for reprocessing requests. 126 127 Capture non-reprocess images for each edge mode and calculate their 128 sharpness as a baseline. 129 130 Capture reprocessed images for each supported reprocess format and edge_mode 131 mode. Calculate the sharpness of reprocessed images and compare them against 132 the sharpess of non-reprocess images. 133 """ 134 135 def test_reprocess_edge_enhancement(self): 136 logging.debug('Edge modes: %s', str(EDGE_MODES)) 137 with its_session_utils.ItsSession( 138 device_id=self.dut.serial, 139 camera_id=self.camera_id, 140 hidden_physical_id=self.hidden_physical_id) as cam: 141 props = cam.get_camera_properties() 142 props = cam.override_with_hidden_physical_camera_props(props) 143 log_path = self.log_path 144 145 # Check skip conditions 146 camera_properties_utils.skip_unless( 147 camera_properties_utils.read_3a(props) and 148 camera_properties_utils.per_frame_control(props) and 149 camera_properties_utils.edge_mode(props, 0) and 150 (camera_properties_utils.yuv_reprocess(props) or 151 camera_properties_utils.private_reprocess(props))) 152 153 # Load chart for scene 154 its_session_utils.load_scene( 155 cam, props, self.scene, self.tablet, self.chart_distance) 156 157 # Initialize chart class and locate chart in scene 158 chart = opencv_processing_utils.Chart(cam, props, self.log_path) 159 160 # If reprocessing is supported, ZSL edge mode must be avaiable. 161 if not camera_properties_utils.edge_mode(props, EDGE_MODES['ZSL']): 162 raise AssertionError('ZSL android.edge.mode not available!') 163 164 reprocess_formats = [] 165 if camera_properties_utils.yuv_reprocess(props): 166 reprocess_formats.append('yuv') 167 if camera_properties_utils.private_reprocess(props): 168 reprocess_formats.append('private') 169 170 size = capture_request_utils.get_available_output_sizes('jpg', props)[0] 171 logging.debug('image W: %d, H: %d', size[0], size[1]) 172 out_surface = {'width': size[0], 'height': size[1], 'format': 'jpg'} 173 174 # Get proper sensitivity, exposure time, and focus distance. 175 mono_camera = camera_properties_utils.mono_camera(props) 176 s, e, _, _, fd = cam.do_3a(get_results=True, mono_camera=mono_camera) 177 178 # Initialize plot 179 pylab.figure('reprocess_result') 180 pylab.suptitle(NAME) 181 pylab.title(str(EDGE_MODES)) 182 pylab.xlabel('Edge Enhancement Mode') 183 pylab.ylabel('Image Sharpness') 184 pylab.xticks(EDGE_MODES_VALUES) 185 186 # Get the sharpness for each edge mode for regular requests 187 sharpness_regular = [] 188 edge_mode_reported_regular = [] 189 for edge_mode in EDGE_MODES.values(): 190 # Skip unavailable modes 191 if not camera_properties_utils.edge_mode(props, edge_mode): 192 edge_mode_reported_regular.append(edge_mode) 193 sharpness_regular.append(0) 194 continue 195 ret = do_capture_and_determine_sharpness( 196 cam, edge_mode, s, e, fd, out_surface, chart, log_path) 197 edge_mode_reported_regular.append(ret['edge_mode']) 198 sharpness_regular.append(ret['sharpness']) 199 200 pylab.plot(EDGE_MODES_VALUES, sharpness_regular, 201 '-'+PLOT_COLORS['none']+'o', label='None') 202 logging.debug('Sharpness for edge modes with regular request: %s', 203 str(sharpness_regular)) 204 205 # Get sharpness for each edge mode and reprocess format 206 sharpnesses_reprocess = [] 207 edge_mode_reported_reprocess = [] 208 209 for reprocess_format in reprocess_formats: 210 # List of sharpness 211 sharpnesses = [] 212 edge_mode_reported = [] 213 for edge_mode in range(4): 214 # Skip unavailable modes 215 if not camera_properties_utils.edge_mode(props, edge_mode): 216 edge_mode_reported.append(edge_mode) 217 sharpnesses.append(0) 218 continue 219 220 ret = do_capture_and_determine_sharpness( 221 cam, edge_mode, s, e, fd, out_surface, chart, log_path, 222 reprocess_format) 223 edge_mode_reported.append(ret['edge_mode']) 224 sharpnesses.append(ret['sharpness']) 225 226 sharpnesses_reprocess.append(sharpnesses) 227 edge_mode_reported_reprocess.append(edge_mode_reported) 228 229 # Add to plot and log results 230 pylab.plot(EDGE_MODES_VALUES, sharpnesses, 231 '-'+PLOT_COLORS[reprocess_format]+'o', 232 label=reprocess_format) 233 logging.debug('Sharpness for edge modes w/ %s reprocess fmt: %s', 234 reprocess_format, str(sharpnesses)) 235 # Finalize plot 236 pylab.legend(numpoints=1, fancybox=True) 237 matplotlib.pyplot.savefig('%s_plot.png' % 238 os.path.join(log_path, NAME)) 239 logging.debug('Check regular requests') 240 check_edge_modes(sharpness_regular) 241 242 for reprocess_format in range(len(reprocess_formats)): 243 logging.debug('Check reprocess format: %s', reprocess_format) 244 check_edge_modes(sharpnesses_reprocess[reprocess_format]) 245 246 # Check reprocessing doesn't make everyting worse 247 hq_div_off_reprocess = ( 248 sharpnesses_reprocess[reprocess_format][EDGE_MODES['HQ']] / 249 sharpnesses_reprocess[reprocess_format][EDGE_MODES['OFF']]) 250 hq_div_off_regular = ( 251 sharpness_regular[EDGE_MODES['HQ']] / 252 sharpness_regular[EDGE_MODES['OFF']]) 253 logging.debug('Verify reprocess HQ ~= reg HQ relative to OFF') 254 if hq_div_off_reprocess < hq_div_off_regular*(1-SHARPNESS_RTOL): 255 raise AssertionError( 256 f'HQ/OFF_{reprocess_format}: {hq_div_off_reprocess:.4f}, ' 257 f'HQ/OFF_reg: {hq_div_off_regular:.4f}, RTOL: {SHARPNESS_RTOL}') 258 259 260if __name__ == '__main__': 261 test_runner.main() 262 263