Пример #1
0
    def __init__(self,
                 noiseLevel=0.0,
                 doForeground=True,
                 doBackground=False,
                 dynamic=True,
                 noiseThickness=1):
        """
    noiseLevel -- Amount of noise to add, from 0 to 1.0. For black and white
      images, this means the values of noiseLevel fraction of the pixels will
      be flipped (e.g. noiseLevel of 0.2 flips 20 percent of the pixels). For
      grayscale images, each pixel will be modified by up to 255 * noiseLevel
      (either upwards or downwards).
    doForeground -- Whether to add noise to the foreground. For black and white
      images, black pixels are foreground and white pixels are background. For
      grayscale images, any pixel which does not equal the background color
      (the ImageSensor 'background' parameter) is foreground, and the rest is
      background.
    doBackground -- Whether to add noise to the background (see above).
    """

        BaseFilter.__init__(self)

        self.noiseLevel = noiseLevel
        self.doForeground = doForeground
        self.doBackground = doBackground
        self.dynamic = dynamic
        self.noiseThickness = noiseThickness

        # Generate and save our random state
        saveState = numpy.random.get_state()
        numpy.random.seed(0)
        self._randomState = numpy.random.get_state()
        numpy.random.set_state(saveState)
Пример #2
0
  def __init__(self, factor=1.0, scaleTowardCenter=False):
    """
    Parameters
    ----------
    factor: float
      How much contrast to produce in the output image relative
      to the input image. A factor of 0 returns a solid gray image,
      a factor of 1.0 returns the original image, and higher values
      return higher-contrast images.

    scaleTowardCenter: bool
      If False (the default), uses PIL.ImageEnhance.Contrast.
      If True, scales the pixel values toward 0.5.
    """

    BaseFilter.__init__(self)

    if factor < 0:
      raise ValueError("'factor' must be nonnegative")

    self.factor = factor
    self.scaleTowardCenter = scaleTowardCenter
    if scaleTowardCenter and not (0.0 <= factor <= 1.0):
      raise ValueError("scaleTowardCenter only supports contrast factors "
          "between 0 and 1, inclusive.")
Пример #3
0
    def __init__(self,
                 angles=[0],
                 expand=False,
                 targetRatio=None,
                 highQuality=True):
        """
    angles -- List of angles by which to rotate, in degrees.
    expand -- Whether to expand the output image to contain the entire
      rotated image. If False, the output image will match the dimensions of
      the input image, but cropping may occur.
    targetRatio -- Ratio of the sensor. If specified, used if expand == False
      to grow the image to the target ratio to avoid unnecessary clipping.
    highQuality -- Whether to use bicubic interpolation for rotating.
      instead of nearest neighbor.
    """

        BaseFilter.__init__(self)

        self.angles = angles
        self.expand = expand
        self.targetRatio = targetRatio
        self.highQuality = highQuality
        if not expand:
            for i, angle in enumerate(angles):
                if angle != 0 and angle % 90 == 0:
                    angles[i] -= .01  # Oh, PIL...
Пример #4
0
  def __init__(self, xsize, ysize, c, preserveCenterResolution=False, Debug=False):
    """
    Initializes the kernel matrices, a one-time cost, which are then applied to
    each image.

    @param xsize -- The x-dimension size of the desired output
    @param ysize -- The y-dimension size of the desired output
    @param c     -- Paramaterizes how much the image bends (ie. how steep the
                    fish-eye.  c=0 is no distortion.  c=3 is severe.
    @param preserveCenterResolution -- if True, the resolution of the center of the
                    image will be preserved and the edges will be sub-sampled.
                    If False, the center pixels will be blown up to keep the
                    outside corners at the original resolution.
    @param Debug -- Determines whether to compute and save some intermediate
                    data structures for debugging (deltaxmat, deltaymat, scales).
    """

    BaseFilter.__init__(self)

    # Init params
    self._lastOutputImage = None
    self._xsize = xsize
    self._ysize = ysize
    self._c = c
    self._pcr = preserveCenterResolution
    self._debug = Debug
    self._kernelx = None
    self._kernely = None
    self._kernel = None
    self._imgSize = (-1,-1)
Пример #5
0
  def __init__(self, noiseLevel=0.0, doForeground=True, doBackground=False,
               dynamic=True, noiseThickness=1):
    """
    noiseLevel -- Amount of noise to add, from 0 to 1.0. For black and white
      images, this means the values of noiseLevel fraction of the pixels will
      be flipped (e.g. noiseLevel of 0.2 flips 20 percent of the pixels). For
      grayscale images, each pixel will be modified by up to 255 * noiseLevel
      (either upwards or downwards).
    doForeground -- Whether to add noise to the foreground. For black and white
      images, black pixels are foreground and white pixels are background. For
      grayscale images, any pixel which does not equal the background color
      (the ImageSensor 'background' parameter) is foreground, and the rest is
      background.
    doBackground -- Whether to add noise to the background (see above).
    """

    BaseFilter.__init__(self)

    self.noiseLevel = noiseLevel
    self.doForeground = doForeground
    self.doBackground = doBackground
    self.dynamic = dynamic
    self.noiseThickness = noiseThickness

    # Generate and save our random state
    saveState = numpy.random.get_state()
    numpy.random.seed(0)
    self._randomState = numpy.random.get_state()
    numpy.random.set_state(saveState)
Пример #6
0
    def __init__(self,
                 xsize,
                 ysize,
                 c,
                 preserveCenterResolution=False,
                 Debug=False):
        """
    Initializes the kernel matrices, a one-time cost, which are then applied to
    each image.

    @param xsize -- The x-dimension size of the desired output
    @param ysize -- The y-dimension size of the desired output
    @param c     -- Paramaterizes how much the image bends (ie. how steep the
                    fish-eye.  c=0 is no distortion.  c=3 is severe.
    @param preserveCenterResolution -- if True, the resolution of the center of the
                    image will be preserved and the edges will be sub-sampled.
                    If False, the center pixels will be blown up to keep the
                    outside corners at the original resolution.
    @param Debug -- Determines whether to compute and save some intermediate
                    data structures for debugging (deltaxmat, deltaymat, scales).
    """

        BaseFilter.__init__(self)

        # Init params
        self._lastOutputImage = None
        self._xsize = xsize
        self._ysize = ysize
        self._c = c
        self._pcr = preserveCenterResolution
        self._debug = Debug
        self._kernelx = None
        self._kernely = None
        self._kernel = None
        self._imgSize = (-1, -1)
Пример #7
0
    def __init__(self, shiftSize=1):
        """
    @param stepSize -- number of pixels to shift
    """

        BaseFilter.__init__(self)

        self.shiftSize = shiftSize
Пример #8
0
  def __init__(self, shiftSize=1):
    """
    @param stepSize -- number of pixels to shift
    """

    BaseFilter.__init__(self)

    self.shiftSize = shiftSize
Пример #9
0
  def __init__(self, level=1):
    """
    @param level -- Number of times to blur.
    """

    BaseFilter.__init__(self)

    self.level = level
Пример #10
0
  def __init__(self, level=1):
    """
    @param level -- Number of times to blur.
    """

    BaseFilter.__init__(self)

    self.level = level
Пример #11
0
 def __init__(self, difficulty = 0.5, seed=None, reproducible=False):
   """
   @param seed -- Seed value for random number generator, to produce
     reproducible results.
   @param reproducible -- Whether to seed the random number generator based
     on a hash of the image pixels upon each call to process().
   'seed' and 'reproducible' cannot be used together.
   """
   BaseFilter.__init__(self, seed, reproducible)
Пример #12
0
 def __init__(self, difficulty=0.5, seed=None, reproducible=False):
     """
 @param seed -- Seed value for random number generator, to produce
   reproducible results.
 @param reproducible -- Whether to seed the random number generator based
   on a hash of the image pixels upon each call to process().
 'seed' and 'reproducible' cannot be used together.
 """
     BaseFilter.__init__(self, seed, reproducible)
Пример #13
0
    def __init__(self, width, height):
        """
    ** DEPRECATED **
    @param width -- Target width, in pixels.
    @param height -- Target height, in pixels.
    """

        BaseFilter.__init__(self)

        self.width = width
        self.height = height
Пример #14
0
 def __init__(self, seed=None, reproducible=False, both=False):
     """
 @param seed -- Seed value for random number generator, to produce
   reproducible results.
 @param reproducible -- Whether to seed the random number generator based
   on a hash of the image pixels upon each call to process().
 'seed' and 'reproducible' cannot be used together.
 both -- Whether to also pass through the original image.
 """
     BaseFilter.__init__(self, seed, reproducible)
     self.both = both
Пример #15
0
  def __init__(self, box):
    """
    @param box -- 4-tuple specifying the left, top, right, and bottom coords.
    """

    BaseFilter.__init__(self)

    if box[2] <= box[0] or box[3] <= box[1]:
      raise RuntimeError('Specified box has zero width or height')

    self.box = box
Пример #16
0
 def __init__(self, seed=None, reproducible=False, both=False):
     """
 @param seed -- Seed value for random number generator, to produce
   reproducible results.
 @param reproducible -- Whether to seed the random number generator based
   on a hash of the image pixels upon each call to process().
 'seed' and 'reproducible' cannot be used together.
 both -- Whether to also pass through the original image.
 """
     BaseFilter.__init__(self, seed, reproducible)
     self.both = both
Пример #17
0
  def __init__(self, width, height):
    """
    ** DEPRECATED **
    @param width -- Target width, in pixels.
    @param height -- Target height, in pixels.
    """

    BaseFilter.__init__(self)

    self.width = width
    self.height = height
Пример #18
0
  def __init__(self, factor=1.0):
    """
    @param factor -- Factor by which to brighten the image, a nonnegative
      number. 0.0 returns a black image, 1.0 returns the original image, and
      higher values return brighter images.
    """

    BaseFilter.__init__(self)

    if factor < 0:
      raise ValueError("'factor' must be a nonnegative number")

    self.factor = factor
Пример #19
0
 def __init__(self, difficulty = 0.5, seed=None, reproducible=False):
   """
   @param difficulty -- Value between 0.0 and 1.0 that controls the intensity of the gradient applied.
   @param seed -- Seed value for random number generator, to produce
     reproducible results.
   @param reproducible -- Whether to seed the random number generator based
     on a hash of the image pixels upon each call to process().
   'seed' and 'reproducible' cannot be used together.
   """
   BaseFilter.__init__(self, seed, reproducible)
   self.difficulty = difficulty
   self.types = ('horizontal', 'vertical', 'circular')
   self.gradientImages = {}
Пример #20
0
 def __init__(self, difficulty = 0.5, seed=None, reproducible=False):
   """
   @param difficulty -- Value between 0.0 and 1.0 that controls how many lines to add in image.
   @param seed -- Seed value for random number generator, to produce
     reproducible results.
   @param reproducible -- Whether to seed the random number generator based
     on a hash of the image pixels upon each call to process().
   'seed' and 'reproducible' cannot be used together.
   """
   BaseFilter.__init__(self, seed, reproducible)
   self.difficulty = difficulty
   #Maximum number of lines to add
   self.maxLines = 10
Пример #21
0
    def __init__(self, factor=1.0):
        """
    @param factor -- Factor by which to brighten the image, a nonnegative
      number. 0.0 returns a black image, 1.0 returns the original image, and
      higher values return brighter images.
    """

        BaseFilter.__init__(self)

        if factor < 0:
            raise ValueError("'factor' must be a nonnegative number")

        self.factor = factor
Пример #22
0
  def __init__(self, numRectangles=4, seed=None, reproducible=False):
    """
    @param numRectangles -- Number of rectangles to add.
    @param seed -- Seed value for random number generator, to produce
      reproducible results.
    @param reproducible -- Whether to seed the random number generator based
      on a hash of the image pixels upon each call to process().
    'seed' and 'reproducible' cannot be used together.
    """

    BaseFilter.__init__(self, seed, reproducible)

    self.numRectangles = numRectangles
Пример #23
0
  def __init__(self, numRectangles=4, seed=None, reproducible=False):
    """
    @param numRectangles -- Number of rectangles to add.
    @param seed -- Seed value for random number generator, to produce
      reproducible results.
    @param reproducible -- Whether to seed the random number generator based
      on a hash of the image pixels upon each call to process().
    'seed' and 'reproducible' cannot be used together.
    """

    BaseFilter.__init__(self, seed, reproducible)

    self.numRectangles = numRectangles
Пример #24
0
 def __init__(self, difficulty=0.5, seed=None, reproducible=False):
     """
 @param difficulty -- Value between 0.0 and 1.0 that controls how many lines to add in image.
 @param seed -- Seed value for random number generator, to produce
   reproducible results.
 @param reproducible -- Whether to seed the random number generator based
   on a hash of the image pixels upon each call to process().
 'seed' and 'reproducible' cannot be used together.
 """
     BaseFilter.__init__(self, seed, reproducible)
     self.difficulty = difficulty
     #Maximum number of lines to add
     self.maxLines = 10
Пример #25
0
 def __init__(self, difficulty=0.5, seed=None, reproducible=False):
     """
 @param difficulty -- Value between 0.0 and 1.0 that controls the intensity of the gradient applied.
 @param seed -- Seed value for random number generator, to produce
   reproducible results.
 @param reproducible -- Whether to seed the random number generator based
   on a hash of the image pixels upon each call to process().
 'seed' and 'reproducible' cannot be used together.
 """
     BaseFilter.__init__(self, seed, reproducible)
     self.difficulty = difficulty
     self.types = ('horizontal', 'vertical', 'circular')
     self.gradientImages = {}
Пример #26
0
    def __init__(self, scales=[1], simultaneous=False):
        """
    ** DEPRECATED **
    @param scales -- List of factors used for scaling. scales = [.5, 1] returns
      two images, one half the size of the original in each dimension, and one
      which is the original image.
    @param simultaneous -- Whether the images should be sent out of the sensor
      simultaneously.
    """

        BaseFilter.__init__(self)

        self.scales = scales
        self.simultaneous = simultaneous
Пример #27
0
    def __init__(self, img=None, threshold=10, maskScale=1.0, blurRadius=0.0):
        """
    @param img -- path to background image(s) to use
    """

        BaseFilter.__init__(self)

        self.bgPath = img
        self.bgImgs = None
        self._rng = random.Random()
        self._rng.seed(42)
        self._threshold = threshold
        self._maskScale = maskScale
        self._blurRadius = blurRadius
Пример #28
0
  def __init__(self, img=None, threshold=10, maskScale=1.0, blurRadius=0.0):
    """
    @param img -- path to background image(s) to use
    """

    BaseFilter.__init__(self)

    self.bgPath = img
    self.bgImgs = None
    self._rng = random.Random()
    self._rng.seed(42)
    self._threshold = threshold
    self._maskScale = maskScale
    self._blurRadius = blurRadius
Пример #29
0
  def __init__(self, scales=[1], simultaneous=False):
    """
    ** DEPRECATED **
    @param scales -- List of factors used for scaling. scales = [.5, 1] returns
      two images, one half the size of the original in each dimension, and one
      which is the original image.
    @param simultaneous -- Whether the images should be sent out of the sensor
      simultaneously.
    """

    BaseFilter.__init__(self)

    self.scales = scales
    self.simultaneous = simultaneous
Пример #30
0
 def __init__(self, difficulty=0.5, seed=None, reproducible=False):
     """
 @param difficulty -- Controls the amount of stretch and shear applied to the image.
 @param seed -- Seed value for random number generator, to produce
   reproducible results.
 @param reproducible -- Whether to seed the random number generator based
   on a hash of the image pixels upon each call to process().
 'seed' and 'reproducible' cannot be used together.
 """
     BaseFilter.__init__(self, seed, reproducible)
     self.difficulty = difficulty
     self.maxShear = 1.0
     self.maxSqueeze = 0.1
     self.minSqueeze = 1.0
     self.types = ('shear_x', 'shear_y', 'squeeze_x', 'squeeze_y')
Пример #31
0
 def __init__(self, difficulty = 0.5, seed=None, reproducible=False):
   """
   @param difficulty -- Controls the amount of stretch and shear applied to the image.
   @param seed -- Seed value for random number generator, to produce
     reproducible results.
   @param reproducible -- Whether to seed the random number generator based
     on a hash of the image pixels upon each call to process().
   'seed' and 'reproducible' cannot be used together.
   """
   BaseFilter.__init__(self, seed, reproducible)
   self.difficulty = difficulty
   self.maxShear = 1.0
   self.maxSqueeze = 0.1
   self.minSqueeze = 1.0
   self.types = ('shear_x', 'shear_y', 'squeeze_x', 'squeeze_y')
Пример #32
0
  def __init__(self, width, height, scaleHeightTo=None, scaleWidthTo=None, pad=False):
    """
    ** DEPRECATED **
    @param width -- Target width, in pixels.
    @param height -- Target height, in pixels.
    @param pad -- Whether to pad the image with the background color in order
      to fit the specified size exactly.
    """

    BaseFilter.__init__(self)

    self.width = width
    self.height = height
    self.pad = pad
    self.scaleHeightTo = scaleHeightTo
    self.scaleWidthTo = scaleWidthTo
Пример #33
0
  def __init__(self, value=None, threshold=10, maskScale=1.0, blurRadius=0.0):
    """
    @param value -- If None, the background is filled in with the background
      color. Otherwise, it is filled with value. If value is a list, then
      this filter will return multiple images, one for each value
    """

    BaseFilter.__init__(self)

    if hasattr(value, '__len__'):
      self._values = value
    else:
      self._values = [value]
    self._threshold = threshold
    self._maskScale = maskScale
    self._blurRadius = blurRadius
Пример #34
0
  def __init__(self, width, height, scaleHeightTo=None, scaleWidthTo=None, pad=False):
    """
    ** DEPRECATED **
    @param width -- Target width, in pixels.
    @param height -- Target height, in pixels.
    @param pad -- Whether to pad the image with the background color in order
      to fit the specified size exactly.
    """

    BaseFilter.__init__(self)

    self.width = width
    self.height = height
    self.pad = pad
    self.scaleHeightTo = scaleHeightTo
    self.scaleWidthTo = scaleWidthTo
Пример #35
0
    def __init__(
        self,
        targetDims,
        padding=0,
        scales=None,
        fillValue=0,
        fillFromImageWherePossible=True,
        preservationMode=None,
        qualityLevel="antialias",
        dumpDebugImages=False,
        applyAlpha=True,
    ):
        """
    @param qualityLevel -- specifies the quality of the filter to be used
          for resizing image patches; must be one of:
            'nearest', 'bilinear', 'bicubic', 'antialias'
          (in increasing order of quality)
    @param applyAlpha -- if True, we'll "apply" the alpha channel to the image
          before flattening it (from 'LA' to 'L').  This allows you to pass in
          images that are non-rectangular.  If False, the alpha channel will
          just be used to figure out the bounding box of the object (unless
          a tracking box is passed in, in which case alpha is ignored).
          Note: this is only useful if fillFromImageWherePossible=False
    """

        BaseFilter.__init__(self)

        # Apply default for scales
        if scales is None:
            scales = [1.0]

        if type(scales) not in (list, tuple):
            raise ValueError("'scales' must be a list or tuple")
        if type(scales) is tuple:
            scales = list(scales)

        self._applyAlpha = applyAlpha
        self._targetDims = targetDims
        self._padding = padding
        self._scales = scales
        self._fillValue = fillValue
        self._fillFromImageWherePossible = fillFromImageWherePossible
        self._preservationMode = preservationMode
        self._resizingFilter = eval("Image.%s" % qualityLevel.upper())
        self._dumpDebugImages = dumpDebugImages
        if fillValue is None:
            self._histWeights = numpy.array(range(256), dtype="float")
Пример #36
0
    def __init__(self, region="all", mode=None):
        """
    @param region -- Options are 'all' (equalize the entire image), 'bbox'
      (equalize just the portion of the image within the bounding box), and
      'mask' (equalize just the portion of the image within the mask).
    @param mode -- ** DEPRECATED ** Alias for 'region'.
    """

        BaseFilter.__init__(self)

        if mode is not None:
            region = mode

        if region not in ("all", "bbox", "mask"):
            raise RuntimeError("Not a supported region (options are 'all', 'bbox', and 'mask')")

        self.region = region
Пример #37
0
  def __init__(self, difficulty = 0.5, seed=None, reproducible=False):
    """
    @param difficulty -- Value between 0.0 and 1.0 that dictates how far
      to shift the image histogram. The direction will be random, and a random offset will be added.
    @param seed -- Seed value for random number generator, to produce
      reproducible results.
    @param reproducible -- Whether to seed the random number generator based
      on a hash of the image pixels upon each call to process().
    'seed' and 'reproducible' cannot be used together.
    """
    BaseFilter.__init__(self, seed, reproducible)

    if difficulty < 0.0 or difficulty > 1.0:
        raise RuntimeError("difficulty must be between 0.0 and 1.0")
    self.difficulty = difficulty
    #Maximum histogram shift - half the grayscale band (0-255)
    self.maxOffset = 128
Пример #38
0
  def __init__(self, difficulty = 0.5, seed=None, reproducible=False):
    """
    @param difficulty -- Value between 0.0 and 1.0 that dictates how far
      to shift the image histogram. The direction will be random, and a random offset will be added.
    @param seed -- Seed value for random number generator, to produce
      reproducible results.
    @param reproducible -- Whether to seed the random number generator based
      on a hash of the image pixels upon each call to process().
    'seed' and 'reproducible' cannot be used together.
    """
    BaseFilter.__init__(self, seed, reproducible)

    if difficulty < 0.0 or difficulty > 1.0:
        raise RuntimeError("difficulty must be between 0.0 and 1.0")
    self.difficulty = difficulty
    #Maximum histogram shift - half the grayscale band (0-255)
    self.maxOffset = 128
Пример #39
0
    def __init__(self,
                 targetDims,
                 padding=0,
                 scales=None,
                 fillValue=0,
                 fillFromImageWherePossible=True,
                 preservationMode=None,
                 qualityLevel='antialias',
                 dumpDebugImages=False,
                 applyAlpha=True):
        """
    @param qualityLevel -- specifies the quality of the filter to be used
          for resizing image patches; must be one of:
            'nearest', 'bilinear', 'bicubic', 'antialias'
          (in increasing order of quality)
    @param applyAlpha -- if True, we'll "apply" the alpha channel to the image
          before flattening it (from 'LA' to 'L').  This allows you to pass in
          images that are non-rectangular.  If False, the alpha channel will
          just be used to figure out the bounding box of the object (unless
          a tracking box is passed in, in which case alpha is ignored).
          Note: this is only useful if fillFromImageWherePossible=False
    """

        BaseFilter.__init__(self)

        # Apply default for scales
        if scales is None:
            scales = [1.0]

        if type(scales) not in (list, tuple):
            raise ValueError("'scales' must be a list or tuple")
        if type(scales) is tuple:
            scales = list(scales)

        self._applyAlpha = applyAlpha
        self._targetDims = targetDims
        self._padding = padding
        self._scales = scales
        self._fillValue = fillValue
        self._fillFromImageWherePossible = fillFromImageWherePossible
        self._preservationMode = preservationMode
        self._resizingFilter = eval("Image.%s" % qualityLevel.upper())
        self._dumpDebugImages = dumpDebugImages
        if fillValue is None:
            self._histWeights = numpy.array(range(256), dtype='float')
Пример #40
0
  def __init__(self, region='all', mode=None):
    """
    @param region -- Options are 'all' (equalize the entire image), 'bbox'
      (equalize just the portion of the image within the bounding box), and
      'mask' (equalize just the portion of the image within the mask).
    @param mode -- ** DEPRECATED ** Alias for 'region'.
    """

    BaseFilter.__init__(self)

    if mode is not None:
      region = mode

    if region not in ('all', 'bbox', 'mask'):
      raise RuntimeError(
        "Not a supported region (options are 'all', 'bbox', and 'mask')")

    self.region = region
Пример #41
0
    def __init__(self,
                 value=None,
                 threshold=10,
                 maskScale=1.0,
                 blurRadius=0.0):
        """
    @param value -- If None, the background is filled in with the background
      color. Otherwise, it is filled with value. If value is a list, then
      this filter will return multiple images, one for each value
    """

        BaseFilter.__init__(self)

        if hasattr(value, '__len__'):
            self._values = value
        else:
            self._values = [value]
        self._threshold = threshold
        self._maskScale = maskScale
        self._blurRadius = blurRadius
Пример #42
0
  def __init__(self, region='all', mode=None, cutoff=0):
    """
    @param region -- Options are 'all' (equalize the entire image), 'bbox'
      (equalize just the portion of the image within the bounding box), and
      'mask' (equalize just the portion of the image within the mask).
    @param mode -- ** DEPRECATED ** Alias for 'region'.
    @param cutoff -- Number of pixels to clip from each end of the histogram
      before rescaling it.
    """

    BaseFilter.__init__(self)

    if mode is not None:
      region = mode
    if region not in ('all', 'bbox', 'mask'):
      raise RuntimeError(
        "Not a supported region (options are 'all', 'bbox', and 'mask')")
    if type(cutoff) != int or cutoff < 0:
      raise RuntimeError("'cutoff' must be a positive integer")

    self.region = region
    self.cutoff = cutoff
Пример #43
0
  def __init__(self, angles=[0], expand=False, targetRatio=None,
               highQuality=True):
    """
    angles -- List of angles by which to rotate, in degrees.
    expand -- Whether to expand the output image to contain the entire
      rotated image. If False, the output image will match the dimensions of
      the input image, but cropping may occur.
    targetRatio -- Ratio of the sensor. If specified, used if expand == False
      to grow the image to the target ratio to avoid unnecessary clipping.
    highQuality -- Whether to use bicubic interpolation for rotating.
      instead of nearest neighbor.
    """

    BaseFilter.__init__(self)

    self.angles = angles
    self.expand = expand
    self.targetRatio = targetRatio
    self.highQuality = highQuality
    if not expand:
      for i, angle in enumerate(angles):
        if angle != 0 and angle % 90 == 0:
          angles[i] -= .01  # Oh, PIL...
Пример #44
0
    def __init__(self,
                 size=None,
                 sizes=None,
                 method='fit',
                 simultaneous=False,
                 highQuality=False):
        """
    size -- Target size. Either a tuple (width, height), specifying an
      absolute size in pixels, or a single value, specifying a scale factor
      to apply to the current size.
    sizes -- List of target sizes, for creating multiple output images
      for each input image. Each entry in the list must satisfy the
      requirements for the 'size' parameter, above. 'size' and 'sizes'
      may not be used together.
    method -- Method to use for generating new images, one of:
      'fit'     : scale and pad to match new size, preserving aspect ratio
      'crop'    : scale and crop the image to fill the new size
      'stretch' : stretch the image to fill new size, ignoring aspect ratio
      'center'  : center the original image in the new size without scaling
    simultaneous -- Whether the images should be sent out of the sensor
      simultaneously.
    highQuality -- Whether to use high-quality sampling for resizing
      instead of nearest neighbor. If highQuality is True, antialiasing is
      used for downsampling and bicubic interpolation is used for
      upsampling.

    Example usage:

    Resize the incoming image to fit within (320, 240) by scaling so that
    the image fits exactly within (320, 240) but the aspect ratio is
    maintained, and padding with the sensor's background color:
      Resize(size=(320, 240))

    Scale the image to three different sizes: 100% of the original size,
    50% of the original size, and 25% of the original size, and send the
    three images out of the sensor simultaneously as multiple scales:
      Resize(sizes=(1.0, 0.5, 0.25), simultaneous=True)

    Pad the image to fit in a larger image of size (640, 480), centering it
    in the new image:
      Resize(size=(640, 480), method='center')
    """

        BaseFilter.__init__(self)

        if (not size and not sizes) or (size and sizes):
            raise RuntimeError("Must specify either 'size' or 'sizes'")

        if size:
            sizes = [size]

        if type(sizes) not in (list, tuple):
            raise ValueError("Sizes must be a list or tuple")

        if type(sizes) is tuple:
            sizes = list(sizes)

        for i, size in enumerate(sizes):
            if type(size) in (list, tuple):
                if len(size) > 2:
                    raise ValueError(
                        "Size is too long (must be a scalar or 2-tuple)")
            elif type(size) in (int, float):
                if size <= 0:
                    raise ValueError("Sizes must be positive numbers")
                sizes[i] = [size]
            else:
                raise TypeError("Sizes must be positive numbers")

        if method not in ('fit', 'crop', 'stretch', 'center'):
            raise ValueError(
                "Unknown method "
                "(options are 'fit', 'crop', 'stretch', and 'center')")

        self.sizes = sizes
        self.method = method
        self.simultaneous = simultaneous
        self.highQuality = highQuality
Пример #45
0
  def __init__(self,
               scaleDecimation=[1],
               filterDim=9,
               gainConstant=1.0,
               normalizationMethod='fixed',
               perPlaneNormalization=False,
               perPhaseNormalization=True,
               postProcessingMethod='raw',
               postProcessingSlope=1.0,
               postProcessingCenter=0.5,
               postProcessingMin=0.0,
               postProcessingMax=1.0,
               zeroThresholdOut=0.0,
               boundaryMode='constrained',
               offImagePixelValue=0,
               suppressOutsideBox=True,
               forceBoxContraction=False,
               aspectRatio=0.3,
               effectiveWidth=4.5):
    """Initialize the the convolution filter

    @param inputDims: a list of input image sizes in the
          form of 2-tuples (width, height)

    """

    BaseFilter.__init__(self)

    self._scaleDecimation = scaleDecimation
    self._filterDim = filterDim
    self._gainConstant = gainConstant
    self._normalizationMethod = normalizationMethod
    self._perPlaneNormalization = perPlaneNormalization
    self._perPhaseNormalization = perPhaseNormalization
    self._postProcessingMethod = postProcessingMethod
    self._postProcessingSlope = postProcessingSlope
    self._postProcessingCenter = postProcessingCenter
    self._postProcessingMin = postProcessingMin
    self._postProcessingMax = postProcessingMax
    self._zeroThresholdOut = zeroThresholdOut
    self._boundaryMode = boundaryMode
    self._offImagePixelValue = offImagePixelValue
    self._suppressOutsideBox = suppressOutsideBox
    self._forceBoxContraction = forceBoxContraction
    self._aspectRatio = aspectRatio
    self._effectiveWidth = effectiveWidth

    self._filterBank = None
    self._outputPlaneCount = self._calcPlaneCount()

    self._cache = {}
    self._bbox_cache = {}

    # Load the _algorithms C library that contains the fast convolution code
    libAlgorithms = self._loadLibrary("_algorithms")

    # Prepare the C calls
    self._convolutionProc = libAlgorithms.gaborCompute

    # Generate post-processing lookup-tables (LUTs) that will be
    # used by the C implementation
    self._makeLUTs()
Пример #46
0
  def __init__(self,
          #--------------------------------------------------
          # General parameters
          #
          # Width (in pixels) of smooth window for horizontal
          # SMotion strength histogram
          windowX=9,
          # Height (in pixels) of smooth window for vertical
          # SMotion strength histogram
          windowY=9,
          # Smooth window type; must be one of: 'flat', 'hanning',
          # 'hamming', 'bartlett', 'blackman'
          windowType='hanning',

          #--------------------------------------------------
          # Horizontal tightening/splitting parameters
          #
          # Minimum smoothed SMotion strength (summed vertically)
          # for an X position to be considered "strong" (expressed as
          # a fraction of the maximum vertically-summed SMotion)
          heightThresh=0.1,
          # Minimum peak SMotion strength for a secondary lobe
          # (i.e., not the strongest "primary" lobe) to avoid
          # being culled
          secondaryHeightThresh=0.5,
          # Minimum absolute horizontal length (in pixels) that a
          # horizontal strong zone must extend to avoid being
          # culled
          minAbsZoneLenX=5,
          # Minimum relative horizontal length (expressed as a
          # fraction of the total original box width) that a
          # horizontal strong zone must extend to avoid being
          # culled
          minRelZoneLenX=0.15,
          # Minimum horizontal "gap" width (in terms of absolute
          # pixels) which a weak zone must extend to avoid
          # being filled in (if it lies between two strong zones)
          minAbsWeakLenX=5,
          # Minimum horizontal "gap" width (as percentage of the
          # image width) which a weak zone must extend to avoid
          # being filled in (if it lies between two strong zones)
          minRelWeakLenX=0.10,
          # The number of pixels to expand our accepted zones
          # horizontally prior to tightening/splitting
          zonePreExpansionX=16, #8, #0, #8,
          # The number of pixels to expand our accepted zones
          # norizontally following tightening/splitting
          zonePostExpansionX=4, #0, #4,

          #--------------------------------------------------
          # Vertical tightening/splitting parameters
          #
          # Minimum smoothed SMotion strength (summed horizontally)
          # for a Y position to be considered "strong" (expressed as
          # a fraction of the maximum horizontally-summed SMotion)
          widthThresh=0.1,
          # Minimum peak SMotion strength for a secondary lobe
          # (i.e., not the strongest "primary" lobe) to avoid
          # being culled
          secondaryWidthThresh=0.20,
          # Minimum absolute vertical length (in pixels) that a
          # vertical strong zone must extend to avoid being
          # culled
          minAbsZoneLenY=5,
          # Minimum relative vertical length (expressed as a
          # fraction of the total original box height) that a
          # vertical strong zone must extend to avoid being
          # culled
          minRelZoneLenY=0.15,
          # Minimum vertical "gap" width (in terms of absolute
          # pixels) which a weak zone must extend to avoid
          # being filled in (if it lies between two strong zones)
          minAbsWeakLenY=5,
          # Minimum vertical "gap" width (as percentage of the
          # image height) which a weak zone must extend to avoid
          # being filled in (if it lies between two strong zones)
          minRelWeakLenY=0.30,
          # The number of pixels to expand our accepted zones
          # vertically (not yet implemented)
          zonePreExpansionY=16, #8, #0, #8,
          # The number of pixels to expand our accepted zones
          # vertically following tightening/splitting
          zonePostExpansionY=4, #0, #4,

          #---------------------------------
          # Splitting policy
          # Controls what to do if our algorithm wants to split
          # a box.  Valid values are 'union' (take the union of
          # the split pieces) or 'biggest' (use the biggest
          # split box.)
          splitPolicy='biggest',

          #---------------------------------
          # Debugging
          debugMode=False,
          ):
    """
    """

    BaseFilter.__init__(self)

    self._windowX = windowX
    self._windowY = windowY
    self._windowType = windowType
    self._heightThresh = heightThresh
    self._secondaryHeightThresh = secondaryHeightThresh
    self._minAbsZoneLenX = minAbsZoneLenX
    self._minRelZoneLenX = minRelZoneLenX
    self._minAbsWeakLenX = minAbsWeakLenX
    self._minRelWeakLenX = minRelWeakLenX
    self._zonePreExpansionX = zonePreExpansionX
    self._zonePostExpansionX = zonePostExpansionX
    self._widthThresh = widthThresh
    self._secondaryWidthThresh = secondaryWidthThresh
    self._minAbsZoneLenY = minAbsZoneLenY
    self._minRelZoneLenY = minRelZoneLenY
    self._minAbsWeakLenY = minAbsWeakLenY
    self._minRelWeakLenY = minRelWeakLenY
    self._zonePreExpansionY = zonePreExpansionY
    self._zonePostExpansionY = zonePostExpansionY
    self._splitPolicy = splitPolicy
    self._debugMode = debugMode

    # Counts how many images we've processed
    self._imgCounter = 0
Пример #47
0
    def __init__(
        self,
        #--------------------------------------------------
        # General parameters
        #
        # Width (in pixels) of smooth window for horizontal
        # SMotion strength histogram
        windowX=9,
        # Height (in pixels) of smooth window for vertical
        # SMotion strength histogram
        windowY=9,
        # Smooth window type; must be one of: 'flat', 'hanning',
        # 'hamming', 'bartlett', 'blackman'
        windowType='hanning',

        #--------------------------------------------------
        # Horizontal tightening/splitting parameters
        #
        # Minimum smoothed SMotion strength (summed vertically)
        # for an X position to be considered "strong" (expressed as
        # a fraction of the maximum vertically-summed SMotion)
        heightThresh=0.1,
        # Minimum peak SMotion strength for a secondary lobe
        # (i.e., not the strongest "primary" lobe) to avoid
        # being culled
        secondaryHeightThresh=0.5,
        # Minimum absolute horizontal length (in pixels) that a
        # horizontal strong zone must extend to avoid being
        # culled
        minAbsZoneLenX=5,
        # Minimum relative horizontal length (expressed as a
        # fraction of the total original box width) that a
        # horizontal strong zone must extend to avoid being
        # culled
        minRelZoneLenX=0.15,
        # Minimum horizontal "gap" width (in terms of absolute
        # pixels) which a weak zone must extend to avoid
        # being filled in (if it lies between two strong zones)
        minAbsWeakLenX=5,
        # Minimum horizontal "gap" width (as percentage of the
        # image width) which a weak zone must extend to avoid
        # being filled in (if it lies between two strong zones)
        minRelWeakLenX=0.10,
        # The number of pixels to expand our accepted zones
        # horizontally prior to tightening/splitting
        zonePreExpansionX=16,  #8, #0, #8,
        # The number of pixels to expand our accepted zones
        # norizontally following tightening/splitting
        zonePostExpansionX=4,  #0, #4,

        #--------------------------------------------------
        # Vertical tightening/splitting parameters
        #
        # Minimum smoothed SMotion strength (summed horizontally)
        # for a Y position to be considered "strong" (expressed as
        # a fraction of the maximum horizontally-summed SMotion)
        widthThresh=0.1,
        # Minimum peak SMotion strength for a secondary lobe
        # (i.e., not the strongest "primary" lobe) to avoid
        # being culled
        secondaryWidthThresh=0.20,
        # Minimum absolute vertical length (in pixels) that a
        # vertical strong zone must extend to avoid being
        # culled
        minAbsZoneLenY=5,
        # Minimum relative vertical length (expressed as a
        # fraction of the total original box height) that a
        # vertical strong zone must extend to avoid being
        # culled
        minRelZoneLenY=0.15,
        # Minimum vertical "gap" width (in terms of absolute
        # pixels) which a weak zone must extend to avoid
        # being filled in (if it lies between two strong zones)
        minAbsWeakLenY=5,
        # Minimum vertical "gap" width (as percentage of the
        # image height) which a weak zone must extend to avoid
        # being filled in (if it lies between two strong zones)
        minRelWeakLenY=0.30,
        # The number of pixels to expand our accepted zones
        # vertically (not yet implemented)
        zonePreExpansionY=16,  #8, #0, #8,
        # The number of pixels to expand our accepted zones
        # vertically following tightening/splitting
        zonePostExpansionY=4,  #0, #4,

        #---------------------------------
        # Splitting policy
        # Controls what to do if our algorithm wants to split
        # a box.  Valid values are 'union' (take the union of
        # the split pieces) or 'biggest' (use the biggest
        # split box.)
        splitPolicy='biggest',

        #---------------------------------
        # Debugging
        debugMode=False,
    ):
        """
    """

        BaseFilter.__init__(self)

        self._windowX = windowX
        self._windowY = windowY
        self._windowType = windowType
        self._heightThresh = heightThresh
        self._secondaryHeightThresh = secondaryHeightThresh
        self._minAbsZoneLenX = minAbsZoneLenX
        self._minRelZoneLenX = minRelZoneLenX
        self._minAbsWeakLenX = minAbsWeakLenX
        self._minRelWeakLenX = minRelWeakLenX
        self._zonePreExpansionX = zonePreExpansionX
        self._zonePostExpansionX = zonePostExpansionX
        self._widthThresh = widthThresh
        self._secondaryWidthThresh = secondaryWidthThresh
        self._minAbsZoneLenY = minAbsZoneLenY
        self._minRelZoneLenY = minRelZoneLenY
        self._minAbsWeakLenY = minAbsWeakLenY
        self._minRelWeakLenY = minRelWeakLenY
        self._zonePreExpansionY = zonePreExpansionY
        self._zonePostExpansionY = zonePostExpansionY
        self._splitPolicy = splitPolicy
        self._debugMode = debugMode

        # Counts how many images we've processed
        self._imgCounter = 0
Пример #48
0
  def __init__(self,
               size=None,
               sizes=None,
               method='fit',
               simultaneous=False,
               highQuality=False):
    """
    size -- Target size. Either a tuple (width, height), specifying an
      absolute size in pixels, or a single value, specifying a scale factor
      to apply to the current size.
    sizes -- List of target sizes, for creating multiple output images
      for each input image. Each entry in the list must satisfy the
      requirements for the 'size' parameter, above. 'size' and 'sizes'
      may not be used together.
    method -- Method to use for generating new images, one of:
      'fit'     : scale and pad to match new size, preserving aspect ratio
      'crop'    : scale and crop the image to fill the new size
      'stretch' : stretch the image to fill new size, ignoring aspect ratio
      'center'  : center the original image in the new size without scaling
    simultaneous -- Whether the images should be sent out of the sensor
      simultaneously.
    highQuality -- Whether to use high-quality sampling for resizing
      instead of nearest neighbor. If highQuality is True, antialiasing is
      used for downsampling and bicubic interpolation is used for
      upsampling.

    Example usage:

    Resize the incoming image to fit within (320, 240) by scaling so that
    the image fits exactly within (320, 240) but the aspect ratio is
    maintained, and padding with the sensor's background color:
      Resize(size=(320, 240))

    Scale the image to three different sizes: 100% of the original size,
    50% of the original size, and 25% of the original size, and send the
    three images out of the sensor simultaneously as multiple scales:
      Resize(sizes=(1.0, 0.5, 0.25), simultaneous=True)

    Pad the image to fit in a larger image of size (640, 480), centering it
    in the new image:
      Resize(size=(640, 480), method='center')
    """

    BaseFilter.__init__(self)

    if (not size and not sizes) or (size and sizes):
      raise RuntimeError("Must specify either 'size' or 'sizes'")

    if size:
      sizes = [size]

    if type(sizes) not in (list, tuple):
      raise ValueError("Sizes must be a list or tuple")

    if type(sizes) is tuple:
      sizes = list(sizes)

    for i, size in enumerate(sizes):
      if type(size) in (list, tuple):
        if len(size) > 2:
          raise ValueError("Size is too long (must be a scalar or 2-tuple)")
      elif type(size) in (int, float):
        if size <= 0:
          raise ValueError("Sizes must be positive numbers")
        sizes[i] = [size]
      else:
        raise TypeError("Sizes must be positive numbers")

    if method not in ('fit', 'crop', 'stretch', 'center'):
      raise ValueError("Unknown method "
                       "(options are 'fit', 'crop', 'stretch', and 'center')")

    self.sizes = sizes
    self.method = method
    self.simultaneous = simultaneous
    self.highQuality = highQuality
Пример #49
0
  def __init__(self,
               scaleDecimation=[1],
               filterDim=9,
               gainConstant=1.0,
               normalizationMethod='fixed',
               perPlaneNormalization=False,
               perPhaseNormalization=True,
               postProcessingMethod='raw',
               postProcessingSlope=1.0,
               postProcessingCenter=0.5,
               postProcessingMin=0.0,
               postProcessingMax=1.0,
               zeroThresholdOut=0.0,
               boundaryMode='constrained',
               offImagePixelValue=0,
               suppressOutsideBox=True,
               forceBoxContraction=False,
               aspectRatio=0.3,
               effectiveWidth=4.5):
    """Initialize the the convolution filter

    @param inputDims: a list of input image sizes in the
          form of 2-tuples (width, height)

    """

    BaseFilter.__init__(self)

    self._scaleDecimation = scaleDecimation
    self._filterDim = filterDim
    self._gainConstant = gainConstant
    self._normalizationMethod = normalizationMethod
    self._perPlaneNormalization = perPlaneNormalization
    self._perPhaseNormalization = perPhaseNormalization
    self._postProcessingMethod = postProcessingMethod
    self._postProcessingSlope = postProcessingSlope
    self._postProcessingCenter = postProcessingCenter
    self._postProcessingMin = postProcessingMin
    self._postProcessingMax = postProcessingMax
    self._zeroThresholdOut = zeroThresholdOut
    self._boundaryMode = boundaryMode
    self._offImagePixelValue = offImagePixelValue
    self._suppressOutsideBox = suppressOutsideBox
    self._forceBoxContraction = forceBoxContraction
    self._aspectRatio = aspectRatio
    self._effectiveWidth = effectiveWidth

    self._filterBank = None
    self._outputPlaneCount = self._calcPlaneCount()

    self._cache = {}
    self._bbox_cache = {}

    # Load the _algorithms C library that contains the fast convolution code
    libAlgorithms = self._loadLibrary("_algorithms")

    # Prepare the C calls
    self._convolutionProc = libAlgorithms.gaborCompute

    # Generate post-processing lookup-tables (LUTs) that will be
    # used by the C implementation
    self._makeLUTs()