1# Copyright 2014 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 15# --------------------------------------------------------------------------- # 16# The Google Python style guide should be used for scripts: # 17# http://google-styleguide.googlecode.com/svn/trunk/pyguide.html # 18# --------------------------------------------------------------------------- # 19 20# The ITS modules that are in the utils directory. To see formatted 21# docs, use the "pydoc" command: 22# 23# > pydoc image_processing_utils 24# 25"""Tutorial script for CameraITS tests.""" 26import capture_request_utils 27import image_processing_utils 28import its_base_test 29import its_session_utils 30 31# Standard Python modules. 32import logging 33import os.path 34 35# Modules from the numpy, scipy, and matplotlib libraries. These are used for 36# the image processing code, and images are represented as numpy arrays. 37from matplotlib import pyplot as plt 38import numpy 39 40# Module for Mobly 41from mobly import test_runner 42 43# A convention in each script is to use the filename (without the extension) 44# as the name of the test, when printing results to the screen or dumping files. 45_NAME = os.path.basename(__file__).split('.')[0] 46 47 48# Each script has a class definition 49class TutorialTest(its_base_test.ItsBaseTest): 50 """Test the validity of some metadata entries. 51 52 Looks at the capture results and at the camera characteristics objects. 53 Script uses a config.yml file in the CameraITS directory. 54 A sample config.yml file: 55 TestBeds: 56 - Name: TEST_BED_TUTORIAL 57 Controllers: 58 AndroidDevice: 59 - serial: 03281FDD40008Y 60 label: dut 61 TestParams: 62 camera: "1" 63 scene: "0" 64 65 A sample script call: 66 python tests/tutorial.py --config config.yml 67 68 """ 69 70 def test_tutorial(self): 71 # Each script has a string description of what it does. This is the first 72 # entry inside the main function. 73 """Tutorial script to show how to use the ITS infrastructure.""" 74 75 # The standard way to open a session with a connected camera device. This 76 # creates a cam object which encapsulates the session and which is active 77 # within the scope of the 'with' block; when the block exits, the camera 78 # session is closed. The device and camera are defined in the config.yml 79 # file. 80 with its_session_utils.ItsSession( 81 device_id=self.dut.serial, 82 camera_id=self.camera_id, 83 hidden_physical_id=self.hidden_physical_id) as cam: 84 85 # Append the log_path to store images in the proper location. 86 # Images will be stored in the test output folder: 87 # /tmp/logs/mobly/$TEST_BED_NAME/$DATE/TutorialTest 88 file_name = os.path.join(self.log_path, _NAME) 89 90 # Get the static properties of the camera device. Returns a Python 91 # associative array object; print it to the console. 92 props = cam.get_camera_properties() 93 logging.debug('props\n%s', str(props)) 94 95 # Grab a YUV frame with manual exposure of sensitivity = 200, exposure 96 # duration = 50ms. 97 req = capture_request_utils.manual_capture_request(200, 50*1000*1000) 98 cap = cam.do_capture(req) 99 100 # Print the properties of the captured frame; width and height are 101 # integers, and the metadata is a Python associative array object. 102 # logging.info will be printed to screen & test_log.INFO 103 # logging.debug to test_log.DEBUG in /tmp/logs/mobly/... directory 104 logging.info('Captured image width: %d, height: %d', 105 cap['width'], cap['height']) 106 logging.debug('metadata\n%s', str(cap['metadata'])) 107 108 # The captured image is YUV420. Convert to RGB, and save as a file. 109 rgbimg = image_processing_utils.convert_capture_to_rgb_image(cap) 110 image_processing_utils.write_image(rgbimg, f'{file_name}_rgb.jpg') 111 112 # Can also get the Y,U,V planes separately; save these to greyscale 113 # files. 114 yimg, uimg, vimg = image_processing_utils.convert_capture_to_planes(cap) 115 image_processing_utils.write_image(yimg, f'{file_name}_y_plane.jpg') 116 image_processing_utils.write_image(uimg, f'{file_name}_u_plane.jpg') 117 image_processing_utils.write_image(vimg, f'{file_name}_v_plane.jpg') 118 119 # Run 3A on the device. In this case, just use the entire image as the 120 # 3A region, and run each of AWB,AE,AF. Can also change the region and 121 # specify independently for each of AE,AWB,AF whether it should run. 122 # 123 # NOTE: This may fail, if the camera isn't pointed at a reasonable 124 # target scene. If it fails, the script will end. The logcat messages 125 # can be inspected to see the status of 3A running on the device. 126 # 127 # If this keeps on failing, try also rebooting the device before 128 # running the test. 129 sens, exp, gains, xform, focus = cam.do_3a(get_results=True) 130 logging.info('AE: sensitivity %d, exposure %dms', sens, exp/1000000.0) 131 logging.info('AWB: gains %s', str(gains)) 132 logging.info('AWB: transform %s', str(xform)) 133 logging.info('AF: distance %.4f', focus) 134 135 # Grab a new manual frame, using the 3A values, and convert it to RGB 136 # and save it to a file too. Note that the 'req' object is just a 137 # Python dictionary that is pre-populated by the capture_request_utils 138 # functions (in this case a default manual capture), and the key/value 139 # pairs in the object can be used to set any field of the capture 140 # request. Here, the AWB gains and transform (CCM) are being used. 141 # Note that the CCM transform is in a rational format in capture 142 # requests, meaning it is an object with integer numerators and 143 # denominators. The 3A routine returns simple floats instead, however, 144 # so a conversion from float to rational must be performed. 145 req = capture_request_utils.manual_capture_request(sens, exp) 146 xform_rat = capture_request_utils.float_to_rational(xform) 147 148 req['android.colorCorrection.transform'] = xform_rat 149 req['android.colorCorrection.gains'] = gains 150 cap = cam.do_capture(req) 151 rgbimg = image_processing_utils.convert_capture_to_rgb_image(cap) 152 image_processing_utils.write_image(rgbimg, f'{file_name}_rgb_2.jpg') 153 154 # log the actual capture request object that was used. 155 logging.debug('req: %s', str(req)) 156 157 # Images are numpy arrays. The dimensions are (h,w,3) when indexing, 158 # in the case of RGB images. Greyscale images are (h,w,1). Pixels are 159 # generally float32 values in the [0,1] range, however some of the 160 # helper functions in image_processing_utils deal with the packed YUV420 161 # and other formats of images that come from the device (and convert 162 # them to float32). 163 # Print the dimensions of the image, and the top-left pixel value, 164 # which is an array of 3 floats. 165 logging.info('RGB image dimensions: %s', str(rgbimg.shape)) 166 logging.info('RGB image top-left pixel: %s', str(rgbimg[0, 0])) 167 168 # Grab a center tile from the image; this returns a new image. Save 169 # this tile image. In this case, the tile is the middle 10% x 10% 170 # rectangle. 171 tile = image_processing_utils.get_image_patch( 172 rgbimg, 0.45, 0.45, 0.1, 0.1) 173 image_processing_utils.write_image(tile, f'{file_name}_rgb_2_tile.jpg') 174 175 # Compute the mean values of the center tile image. 176 rgb_means = image_processing_utils.compute_image_means(tile) 177 logging.info('RGB means: %s', str(rgb_means)) 178 179 # Apply a lookup table to the image, and save the new version. The LUT 180 # is basically a tonemap, and can be used to implement a gamma curve. 181 # In this case, the LUT is used to double the value of each pixel. 182 lut = numpy.array([2*i for i in range(65536)]) 183 rgbimg_lut = image_processing_utils.apply_lut_to_image(rgbimg, lut) 184 image_processing_utils.write_image( 185 rgbimg_lut, f'{file_name}_rgb_2_lut.jpg') 186 187 # Compute a histogram of the luma image, in 256 buckets. 188 yimg, _, _ = image_processing_utils.convert_capture_to_planes(cap) 189 hist, _ = numpy.histogram(yimg*255, 256, (0, 256)) 190 191 # Plot the histogram using matplotlib, and save as a PNG image. 192 plt.plot(range(256), hist.tolist()) 193 plt.xlabel('Luma DN') 194 plt.ylabel('Pixel count') 195 plt.title('Histogram of luma channel of captured image') 196 plt.savefig(f'{file_name}_histogram.png') 197 198 # Capture a frame to be returned as a JPEG. Load it as an RGB image, 199 # then save it back as a JPEG. 200 cap = cam.do_capture(req, cam.CAP_JPEG) 201 rgbimg = image_processing_utils.convert_capture_to_rgb_image(cap) 202 image_processing_utils.write_image(rgbimg, f'{file_name}_jpg.jpg') 203 r, _, _ = image_processing_utils.convert_capture_to_planes(cap) 204 image_processing_utils.write_image(r, f'{file_name}_r.jpg') 205 206# This is the standard boilerplate in each test that allows the script to both 207# be executed directly and imported as a module. 208if __name__ == '__main__': 209 test_runner.main() 210 211