Exemple #1
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

        BaseFilter.process(self, image)

        s = min(image.size)
        sizeRange = [int(0.1 * s), int(0.4 * s)]

        newArray = numpy.array(image.split()[0].getdata())
        newArray.resize(image.size[1], image.size[0])
        for j in xrange(self.numRectangles):
            # Generate random rectange
            size = (self.random.randint(sizeRange[0], sizeRange[1]),
                    self.random.randint(sizeRange[0], sizeRange[1]))
            loc = [
                self.random.randint(0, image.size[1]),
                self.random.randint(0, image.size[0])
            ]
            # Move the location so that the rectangle is centered on it
            loc[0] -= size[0] / 2
            loc[1] -= size[1] / 2
            # Generate random color
            color = self.random.randint(0, 255)
            # Add the rectangle to the image
            newArray[max(0,loc[0]):min(newArray.shape[0], loc[0]+size[0]), \
              max(0,loc[1]):min(newArray.shape[1],loc[1]+size[1])] = color
        newImage = Image.new("L", image.size)
        newImage.putdata([uint(p) for p in newArray.flatten()])
        newImage.putalpha(image.split()[1])
        return newImage
Exemple #2
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    s = min(image.size)
    sizeRange = [int(0.1 * s), int(0.4 * s)]

    newArray = numpy.array(image.split()[0].getdata())
    newArray.resize(image.size[1],image.size[0])
    for j in xrange(self.numRectangles):
      # Generate random rectange
      size = (self.random.randint(sizeRange[0], sizeRange[1]),
        self.random.randint(sizeRange[0], sizeRange[1]))
      loc = [self.random.randint(0,image.size[1]),
             self.random.randint(0,image.size[0])]
      # Move the location so that the rectangle is centered on it
      loc[0] -= size[0]/2
      loc[1] -= size[1]/2
      # Generate random color
      color = self.random.randint(0,255)
      # Add the rectangle to the image
      newArray[max(0,loc[0]):min(newArray.shape[0], loc[0]+size[0]), \
        max(0,loc[1]):min(newArray.shape[1],loc[1]+size[1])] = color
    newImage = Image.new("L", image.size)
    newImage.putdata([uint(p) for p in newArray.flatten()])
    newImage.putalpha(image.split()[1])
    return newImage
Exemple #3
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
        BaseFilter.process(self, image)
        s = min(image.size)
        sizeRange = [0, s]

        imageArray = numpy.array(image.split()[0].getdata())
        newImage = Image.new("LA", image.size)
        newImage.putdata([uint(p) for p in imageArray])
        newImage.putalpha(image.split()[1])
        for i in xrange(int(self.difficulty * self.maxLines)):
            # Generate random line
            start = (random.randint(sizeRange[0], sizeRange[1]),
                     random.randint(sizeRange[0], sizeRange[1]))
            end = (random.randint(sizeRange[0], sizeRange[1]),
                   random.randint(sizeRange[0], sizeRange[1]))

            # Generate random color
            color = random.randint(0, 255)

            # Add the line to the image
            draw = ImageDraw.Draw(newImage)
            draw.line((start, end), fill=color)

        return newImage
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    mode = image.mode;
    originalSize = image.size;
    sizes = [(int(round(image.size[0]*s)), int(round(image.size[1]*s)))
      for s in self.scales]

    resizedImages = []
    for size in sizes:
      if size < image.size:
        resizedImage = image.resize(size,Image.ANTIALIAS)
      else:
        resizedImage = image.resize(size,Image.BICUBIC)
      x = (originalSize[0] - size[0])/2
      y = (originalSize[1] - size[1])/2
      newImage = Image.new(mode,originalSize,self.background)
      newImage.paste(resizedImage,(x,y))
      resizedImages.append(newImage)

    if not self.simultaneous:
      return resizedImages
    else:
      return [resizedImages]
Exemple #5
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.")
Exemple #6
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
        BaseFilter.process(self, image)

        base, alpha = image.split()

        if self.scaleTowardCenter:
            scale = float(self.factor)
            assert base.mode == "L"
            maxValue = 255  # TODO: Determine how to get maximum value __allowed__.
            offset = ((1.0 - self.factor) / 2.0) * maxValue
            newImage = ImageMath.eval(
                "convert(convert(gray, 'F') * scale + offset, mode)",
                gray=base,
                scale=scale,
                offset=offset,
                mode=base.mode,
            )
        else:
            contrastEnhancer = ImageEnhance.Contrast(image.split()[0])
            newImage = contrastEnhancer.enhance(self.factor)

        newImage.putalpha(alpha)

        return newImage
Exemple #7
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)
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    # ---------------------------------------------------------------------------
    # Create the mask around the source image
    mask = image.split()[-1]
    if image.mode[-1] != 'A' or isSimpleBBox(mask):
      mask = createMask(image, threshold=self._threshold, fillHoles=True,
                        backgroundColor=self.background, blurRadius=self._blurRadius,
                        maskScale=self._maskScale)


    # ---------------------------------------------------------------------------
    # Process each value
    newImages = []
    for value in self._values:
      if value is None:
        value = self.background

      bg = ImageChops.constant(image, value)
      newImage = Image.composite(image.split()[0], bg, mask)
      newImage.putalpha(image.split()[-1])
      newImages.append(newImage)

    if len(newImages) == 1:
      return newImages[0]
    else:
      return newImages
Exemple #9
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    # ---------------------------------------------------------------------------
    # Create the mask around the source image
    mask = image.split()[-1]
    if image.mode[-1] != 'A' or isSimpleBBox(mask):
      mask = createMask(image, threshold=self._threshold, fillHoles=True,
                        backgroundColor=self.background, blurRadius=self._blurRadius,
                        maskScale=self._maskScale)


    # ---------------------------------------------------------------------------
    # Process each value
    newImages = []
    for value in self._values:
      if value is None:
        value = self.background

      bg = ImageChops.constant(image, value)
      newImage = Image.composite(image.split()[0], bg, mask)
      newImage.putalpha(image.split()[-1])
      newImages.append(newImage)

    if len(newImages) == 1:
      return newImages[0]
    else:
      return newImages
Exemple #10
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
    BaseFilter.process(self, image)

    base, alpha = image.split()

    if self.scaleTowardCenter:
      scale = float(self.factor)
      assert base.mode == "L"
      maxValue = 255 # TODO: Determine how to get maximum value __allowed__.
      offset = ((1.0 - self.factor) / 2.0) * maxValue
      newImage = ImageMath.eval(
          "convert(convert(gray, 'F') * scale + offset, mode)",
          gray=base,
          scale=scale,
          offset=offset,
          mode=base.mode,
        )
    else:
      contrastEnhancer = ImageEnhance.Contrast(image.split()[0])
      newImage = contrastEnhancer.enhance(self.factor)

    newImage.putalpha(alpha)

    return newImage
Exemple #11
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)
Exemple #12
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)
Exemple #13
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.")
Exemple #14
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

        BaseFilter.process(self, image)

        mode = image.mode
        originalSize = image.size
        sizes = [(int(round(image.size[0] * s)), int(round(image.size[1] * s)))
                 for s in self.scales]

        resizedImages = []
        for size in sizes:
            if size < image.size:
                resizedImage = image.resize(size, Image.ANTIALIAS)
            else:
                resizedImage = image.resize(size, Image.BICUBIC)
            x = (originalSize[0] - size[0]) / 2
            y = (originalSize[1] - size[1]) / 2
            newImage = Image.new(mode, originalSize, self.background)
            newImage.paste(resizedImage, (x, y))
            resizedImages.append(newImage)

        if not self.simultaneous:
            return resizedImages
        else:
            return [resizedImages]
Exemple #15
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...
Exemple #16
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)
Exemple #17
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
        BaseFilter.process(self, image)
        s = min(image.size)
        sizeRange = [0, s]

        imageArray = numpy.array(image.split()[0].getdata())
        newImage = Image.new("LA", image.size)
        newImage.putdata([uint(p) for p in imageArray])
        newImage.putalpha(image.split()[1])
        for i in xrange(int(self.difficulty * self.maxLines)):
            # Generate random line
            start = (random.randint(sizeRange[0], sizeRange[1]), random.randint(sizeRange[0], sizeRange[1]))
            end = (random.randint(sizeRange[0], sizeRange[1]), random.randint(sizeRange[0], sizeRange[1]))

            # Generate random color
            color = random.randint(0, 255)

            # Add the line to the image
            draw = ImageDraw.Draw(newImage)
            draw.line((start, end), fill=color)

        return newImage
Exemple #18
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
        BaseFilter.process(self, image)
        #Create numpy array from image grayscale data and resize to image dimensions
        imageArray = numpy.array(image.split()[0].getdata())
        imageArray.resize(image.size[1], image.size[0])
        #Calculate offset from difficulty level
        offset = self.difficulty * (self.maxOffset)
        #Add random change to offset within window size
        halfWindowSize = 0.1 * offset
        offset = (offset -
                  halfWindowSize) + halfWindowSize * self.random.random() * (
                      (-1)**self.random.randint(1, 2))
        #Apply random direction
        offset *= ((-1)**self.random.randint(1, 2))
        imageArray += offset
        #Recreate PIL image
        newImage = Image.new("L", image.size)
        newImage.putdata([uint(p) for p in imageArray.flatten()])
        newImage.putalpha(image.split()[1])
        return newImage
Exemple #19
0
  def __init__(self, shiftSize=1):
    """
    @param stepSize -- number of pixels to shift
    """

    BaseFilter.__init__(self)

    self.shiftSize = shiftSize
Exemple #20
0
    def __init__(self, shiftSize=1):
        """
    @param stepSize -- number of pixels to shift
    """

        BaseFilter.__init__(self)

        self.shiftSize = shiftSize
Exemple #21
0
    def __init__(self, level=1):
        """
    @param level -- Number of times to blur.
    """

        BaseFilter.__init__(self)

        self.level = level
Exemple #22
0
  def __init__(self, level=1):
    """
    @param level -- Number of times to blur.
    """

    BaseFilter.__init__(self)

    self.level = level
Exemple #23
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
        BaseFilter.process(self, image)
        newImage = ImageOps.flip(image)
        return newImage
Exemple #24
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)
Exemple #25
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
    BaseFilter.process(self, image)
    newImage = ImageOps.flip(image)
    return newImage
Exemple #26
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)
Exemple #27
0
    def process(self, image):
        """
    image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

        BaseFilter.process(self, image)

        if not self.expand and self.targetRatio:
            # Pad the image to the aspect ratio of the sensor
            # This allows us to rotate in expand=False without cutting off parts
            # of the image unnecessarily
            # Unlike expand=True, the object doesn't get smaller
            ratio = (image.size[0] / float(image.size[1]))
            if ratio < self.targetRatio:
                # Make image wider
                size = (int(image.size[0] * self.targetRatio / ratio),
                        image.size[1])
                newImage = Image.new('LA', size, (self.background, 0))
                newImage.paste(image,
                               ((newImage.size[0] - image.size[0]) / 2, 0))
                image = newImage
            elif ratio > self.targetRatio:
                # Make image taller
                size = (image.size[0],
                        int(image.size[1] * ratio / self.targetRatio))
                newImage = Image.new('LA', size, (self.background, 0))
                newImage.paste(image,
                               (0, (newImage.size[1] - image.size[1]) / 2))
                image = newImage

        if self.highQuality:
            resample = Image.BICUBIC
        else:
            resample = Image.NEAREST
        outputs = []
        for angle in self.angles:
            # Rotate the image, which expands it and pads it with black and a 0
            # alpha value
            rotatedImage = image.rotate(angle,
                                        resample=resample,
                                        expand=self.expand)

            # Create a new larger image to hold the rotated image
            # It is filled with the background color and an alpha value of 0
            outputImage = Image.new('LA', rotatedImage.size,
                                    (self.background, 0))
            # Paste the rotated image into the new image, using the rotated image's
            # alpha channel as a mask
            # This effectively just fills the area around the rotation with the
            # background color, and imports the alpha channel from the rotated image
            outputImage.paste(rotatedImage, None, rotatedImage.split()[1])
            outputs.append(outputImage)
        return outputs
Exemple #28
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
Exemple #29
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
Exemple #30
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
Exemple #31
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
Exemple #32
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
Exemple #33
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
Exemple #34
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
        BaseFilter.process(self, image)
        newImage = ImageOps.mirror(image)
        if not self.both:
            return newImage
        else:
            return [image, newImage]
Exemple #35
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
    BaseFilter.process(self, image)
    newImage = ImageOps.mirror(image)
    if not self.both:
      return newImage
    else:
      return [image, newImage]
Exemple #36
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
Exemple #37
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    if self.box[2] > image.size[0] or self.box[3] > image.size[1]:
      raise RuntimeError('Crop coordinates exceed image bounds')

    return image.crop(self.box)
Exemple #38
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 = {}
Exemple #39
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
Exemple #40
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
Exemple #41
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    brightnessEnhancer = ImageEnhance.Brightness(image.split()[0])
    newImage = brightnessEnhancer.enhance(self.factor)
    newImage.putalpha(image.split()[1])
    return newImage
Exemple #42
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
Exemple #43
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 = {}
Exemple #44
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

        BaseFilter.process(self, image)

        if self.box[2] > image.size[0] or self.box[3] > image.size[1]:
            raise RuntimeError('Crop coordinates exceed image bounds')

        return image.crop(self.box)
Exemple #45
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
Exemple #46
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
Exemple #47
0
  def process(self, image):
    """
    image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    if not self.expand and self.targetRatio:
      # Pad the image to the aspect ratio of the sensor
      # This allows us to rotate in expand=False without cutting off parts
      # of the image unnecessarily
      # Unlike expand=True, the object doesn't get smaller
      ratio = (image.size[0] / float(image.size[1]))
      if ratio < self.targetRatio:
        # Make image wider
        size = (int(image.size[0] * self.targetRatio / ratio), image.size[1])
        newImage = Image.new('LA', size, (self.background, 0))
        newImage.paste(image, ((newImage.size[0] - image.size[0])/2, 0))
        image = newImage
      elif ratio > self.targetRatio:
        # Make image taller
        size = (image.size[0], int(image.size[1] * ratio / self.targetRatio))
        newImage = Image.new('LA', size, (self.background, 0))
        newImage.paste(image, (0, (newImage.size[1] - image.size[1])/2))
        image = newImage

    if self.highQuality:
      resample = Image.BICUBIC
    else:
      resample = Image.NEAREST
    outputs = []
    for angle in self.angles:
      # Rotate the image, which expands it and pads it with black and a 0
      # alpha value
      rotatedImage = image.rotate(angle,
                                  resample=resample,
                                  expand=self.expand)

      # Create a new larger image to hold the rotated image
      # It is filled with the background color and an alpha value of 0
      outputImage = Image.new('LA', rotatedImage.size, (self.background, 0))
      # Paste the rotated image into the new image, using the rotated image's
      # alpha channel as a mask
      # This effectively just fills the area around the rotation with the
      # background color, and imports the alpha channel from the rotated image
      outputImage.paste(rotatedImage, None, rotatedImage.split()[1])
      outputs.append(outputImage)
    return outputs
  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
    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
Exemple #50
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
    BaseFilter.process(self, image)
    type = self.random.choice(self.types)
    #Default matrix
    matrix = (1, 0, 0, 0, 1, 0)
    size = list(image.size)
    newImage = Image.new('LA', size)
    if type == 'shear_x':
        shear = self.difficulty*self.maxShear - self.difficulty*0.3 + self.difficulty*0.3*self.random.random()
        matrix = (1, shear, -shear*size[1], 0, 1, 0)
        size[0] += int(shear*size[0])
        newImage = image.transform(tuple(size), Image.AFFINE, matrix)
        bbox = list(newImage.split()[1].getbbox())
        bbox[1] = 0
        bbox[3] = size[1]
        newImage = newImage.crop(bbox)
    elif type == 'shear_y':
        shear = self.difficulty*self.maxShear - self.difficulty*0.3 + self.difficulty*0.3*self.random.random()
        matrix = (1, 0, 0, shear, 1, -shear*size[0])
        size[1] += int(shear*size[1])
        newImage = image.transform(tuple(size), Image.AFFINE, matrix)
        bbox = list(newImage.split()[1].getbbox())
        bbox[0] = 0
        bbox[2] = size[0]
        newImage = newImage.crop(bbox)
    elif type == 'squeeze_x':
        squeeze = self.minSqueeze - (self.minSqueeze - self.maxSqueeze)*(self.difficulty - self.difficulty*0.3 + self.difficulty*0.3*self.random.random())
        matrix = (1/squeeze, 0, 0, 0, 1, 0)
        newImage = ImageChops.offset(image.transform(tuple(size), Image.AFFINE, matrix), int((size[0] - squeeze*size[0])/2), 0)
    elif type == 'squeeze_y':
        squeeze = self.minSqueeze - (self.minSqueeze - self.maxSqueeze)*(self.difficulty - self.difficulty*0.3 + self.difficulty*0.3*self.random.random())
        matrix = (1, 0, 0, 0, 1/squeeze, 0)
        newImage = ImageChops.offset(image.transform(tuple(size), Image.AFFINE, matrix), 0, int((size[1] - squeeze*size[1])/2))
    #Appropriate sizing
    if newImage.size[0] > image.size[0] or newImage.size[1] > image.size[1]:
        newImage = newImage.resize(image.size)
    elif newImage.size[1] < image.size[1]:
        retImage = Image.new('LA', image.size)
        retImage.paste(newImage, (0, int((image.size[1] - newImage.size[1])/2.0)))
        newImage = retImage
    elif newImage.size[0] < image.size[0]:
        retImage = Image.new('LA', image.size)
        retImage.paste(newImage, (0, int((image.size[0] - newImage.size[0])/2.0)))
    return newImage
Exemple #51
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    if image.size == (self.width, self.height):
      return image

    # Resize the image
    targetRatio = self.width / float(self.height)
    imageRatio = image.size[0] / float(image.size[1])
    if self.scaleHeightTo:
      ySize = self.scaleHeightTo
      scaleFactor = self.scaleHeightTo / float(image.size[1])
      xSize = int(scaleFactor * image.size[0])
    elif self.scaleWidthTo:
      xSize = self.scaleWidthTo
      scaleFactor = self.scaleWidthTo / float(image.size[0])
      ySize = int(scaleFactor * image.size[1])
    else:
      if imageRatio > targetRatio:
        xSize = self.width
        scaleFactor = self.width / float(image.size[0])
        ySize = int(scaleFactor * image.size[1])
      else:
        ySize = self.height
        scaleFactor = self.height / float(image.size[1])
        xSize = int(scaleFactor * image.size[0])

    if (xSize, ySize) < image.size:
      image = image.resize((xSize, ySize),Image.ANTIALIAS)
    else:
      image = image.resize((xSize, ySize),Image.BICUBIC)

    # Pad the image if necessary
    if self.pad and image.size != (self.width, self.height):
      paddedImage = Image.new('L', (self.width, self.height),
        self.background)
      alpha = Image.new('L', (self.width, self.height))
      paddedImage.putalpha(alpha)
      paddedImage.paste(image,
        ((self.width - image.size[0])/2, (self.height - image.size[1])/2))
      image = paddedImage

    return image
Exemple #52
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

        BaseFilter.process(self, image)

        if image.size == (self.width, self.height):
            return image

        # Resize the image
        targetRatio = self.width / float(self.height)
        imageRatio = image.size[0] / float(image.size[1])
        if self.scaleHeightTo:
            ySize = self.scaleHeightTo
            scaleFactor = self.scaleHeightTo / float(image.size[1])
            xSize = int(scaleFactor * image.size[0])
        elif self.scaleWidthTo:
            xSize = self.scaleWidthTo
            scaleFactor = self.scaleWidthTo / float(image.size[0])
            ySize = int(scaleFactor * image.size[1])
        else:
            if imageRatio > targetRatio:
                xSize = self.width
                scaleFactor = self.width / float(image.size[0])
                ySize = int(scaleFactor * image.size[1])
            else:
                ySize = self.height
                scaleFactor = self.height / float(image.size[1])
                xSize = int(scaleFactor * image.size[0])

        if (xSize, ySize) < image.size:
            image = image.resize((xSize, ySize), Image.ANTIALIAS)
        else:
            image = image.resize((xSize, ySize), Image.BICUBIC)

        # Pad the image if necessary
        if self.pad and image.size != (self.width, self.height):
            paddedImage = Image.new('L', (self.width, self.height),
                                    self.background)
            alpha = Image.new('L', (self.width, self.height))
            paddedImage.putalpha(alpha)
            paddedImage.paste(image, ((self.width - image.size[0]) / 2,
                                      (self.height - image.size[1]) / 2))
            image = paddedImage

        return image
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
    BaseFilter.process(self, image)
    type = self.random.choice(self.types)
    #Default matrix
    matrix = (1, 0, 0, 0, 1, 0)
    size = list(image.size)
    newImage = Image.new('LA', size)
    if type == 'shear_x':
        shear = self.difficulty*self.maxShear - self.difficulty*0.3 + self.difficulty*0.3*self.random.random()
        matrix = (1, shear, -shear*size[1], 0, 1, 0)
        size[0] += int(shear*size[0])
        newImage = image.transform(tuple(size), Image.AFFINE, matrix)
        bbox = list(newImage.split()[1].getbbox())
        bbox[1] = 0
        bbox[3] = size[1]
        newImage = newImage.crop(bbox)
    elif type == 'shear_y':
        shear = self.difficulty*self.maxShear - self.difficulty*0.3 + self.difficulty*0.3*self.random.random()
        matrix = (1, 0, 0, shear, 1, -shear*size[0])
        size[1] += int(shear*size[1])
        newImage = image.transform(tuple(size), Image.AFFINE, matrix)
        bbox = list(newImage.split()[1].getbbox())
        bbox[0] = 0
        bbox[2] = size[0]
        newImage = newImage.crop(bbox)
    elif type == 'squeeze_x':
        squeeze = self.minSqueeze - (self.minSqueeze - self.maxSqueeze)*(self.difficulty - self.difficulty*0.3 + self.difficulty*0.3*self.random.random())
        matrix = (1/squeeze, 0, 0, 0, 1, 0)
        newImage = ImageChops.offset(image.transform(tuple(size), Image.AFFINE, matrix), int((size[0] - squeeze*size[0])/2), 0)
    elif type == 'squeeze_y':
        squeeze = self.minSqueeze - (self.minSqueeze - self.maxSqueeze)*(self.difficulty - self.difficulty*0.3 + self.difficulty*0.3*self.random.random())
        matrix = (1, 0, 0, 0, 1/squeeze, 0)
        newImage = ImageChops.offset(image.transform(tuple(size), Image.AFFINE, matrix), 0, int((size[1] - squeeze*size[1])/2))
    #Appropriate sizing
    if newImage.size[0] > image.size[0] or newImage.size[1] > image.size[1]:
        newImage = newImage.resize(image.size)
    elif newImage.size[1] < image.size[1]:
        retImage = Image.new('LA', image.size)
        retImage.paste(newImage, (0, int((image.size[1] - newImage.size[1])/2.0)))
        newImage = retImage
    elif newImage.size[0] < image.size[0]:
        retImage = Image.new('LA', image.size)
        retImage.paste(newImage, (0, int((image.size[0] - newImage.size[0])/2.0)))
    return newImage
Exemple #54
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

    BaseFilter.process(self, image)

    mask = image.split()[1]
    for i in xrange(self.level):
      sharpness_enhancer = ImageEnhance.Sharpness(image.split()[0])
      image = sharpness_enhancer.enhance(0.0)
    image.putalpha(mask)
    return image
Exemple #55
0
    def process(self, image):
        """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """

        BaseFilter.process(self, image)

        mask = image.split()[1]
        for i in xrange(self.level):
            sharpness_enhancer = ImageEnhance.Sharpness(image.split()[0])
            image = sharpness_enhancer.enhance(0.0)
        image.putalpha(mask)
        return image
Exemple #56
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")
Exemple #57
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