1# Copyright 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import logging
6import os
7import sys
8
9
10class ImageGenerator(object):
11    """A class to generate the calibration images with different sizes.
12
13    It generates the SVG images which are easy to be produced by changing its
14    XML text content.
15
16    """
17
18    TEMPLATE_WIDTH = 1680
19    TEMPLATE_HEIGHT = 1052
20    TEMPLATE_FILENAME = 'template-%dx%d.svg' % (TEMPLATE_WIDTH, TEMPLATE_HEIGHT)
21
22
23    def __init__(self):
24        """Construct an ImageGenerator.
25        """
26        module_dir = os.path.dirname(sys.modules[__name__].__file__)
27        template_path = os.path.join(module_dir, 'calibration_images',
28                                     self.TEMPLATE_FILENAME)
29        self._image_template = open(template_path).read()
30
31
32    def generate_image(self, width, height, filename):
33        """Generate the image with the given width and height.
34
35        @param width: The width of the image.
36        @param height: The height of the image.
37        @param filename: The filename to output.
38        """
39        with open(filename, 'w+') as f:
40            logging.debug('Generate the image with size %dx%d to %s',
41                          width, height, filename)
42            f.write(self._image_template.format(
43                    scale_width=float(width)/self.TEMPLATE_WIDTH,
44                    scale_height=float(height)/self.TEMPLATE_HEIGHT))
45
46    @staticmethod
47    def get_extrema(image):
48        """Returns a 2-tuple containing minimum and maximum values of the image.
49
50        @param image: the calibration image projected by DUT.
51        @return a tuple of (minimum, maximum)
52        """
53        w, h = image.size
54        min_value = 255
55        max_value = 0
56        # scan the middle vertical line
57        x = w / 2
58        for i in range(0, h/2):
59            v = image.getpixel((x, i))[0]
60            if v < min_value:
61                min_value = v
62            if v > max_value:
63                max_value = v
64        return (min_value, max_value)
65