Augment a batch by randomly cropping and horizontally flipping it.
965959
def random_crop_and_flip(x, pad_rows=4, pad_cols=4):
  """"""
  rows = tf.shape(x)[1]
  cols = tf.shape(x)[2]
  channels = x.get_shape()[3]

  def _rand_crop_img(img):
    """Randomly crop an individual image"""
    return tf.random_crop(img, [rows, cols, channels])

  # Some of these ops are only on CPU.
  # This function will often be called with the device set to GPU.
  # We need to set it to CPU temporarily to avoid an exception.
  with tf.device('/CPU:0'):
    x = tf.image.resize_image_with_crop_or_pad(x, rows + pad_rows,
                                               cols + pad_cols)
    x = tf.map_fn(_rand_crop_img, x)
    x = tf.image.random_flip_left_right(x)
  return x
370508
def parse_crop(crop, xy_image, xy_window):
    

    x_alias_percent = {
        'left': '0%',
        'center': '50%',
        'right': '100%',
    }
    y_alias_percent = {
        'top': '0%',
        'center': '50%',
        'bottom': '100%',
    }
    xy_crop = crop.split(' ')

    if len(xy_crop) == 1:
        if crop in x_alias_percent:
            x_crop = x_alias_percent[crop]
            y_crop = '50%'
        elif crop in y_alias_percent:
            y_crop = y_alias_percent[crop]
            x_crop = '50%'
        else:
            x_crop, y_crop = crop, crop
    elif len(xy_crop) == 2:
        x_crop, y_crop = xy_crop
        x_crop = x_alias_percent.get(x_crop, x_crop)
        y_crop = y_alias_percent.get(y_crop, y_crop)
    else:
        raise ThumbnailParseError('Unrecognized crop option: %s' % crop)

    def get_offset(crop, epsilon):
        m = bgpos_pat.match(crop)
        if not m:
            raise ThumbnailParseError('Unrecognized crop option: %s' % crop)
        value = int(m.group('value'))  # we only take ints in the regexp
        unit = m.group('unit')
        if unit == '%':
            value = epsilon * value / 100.0

        # return ∈ [0, epsilon]
        return int(max(0, min(value, epsilon)))

    offset_x = get_offset(x_crop, xy_image[0] - xy_window[0])
    offset_y = get_offset(y_crop, xy_image[1] - xy_window[1])
    return offset_x, offset_y
1291900
def preprocess(self, image):
        
        image = super(max7219, self).preprocess(image)

        if self._correction_angle != 0:
            image = image.copy()
            for y in range(0, self._h, 8):
                for x in range(0, self._w, 8):
                    box = (x, y, x + 8, y + 8)
                    rotated_block = image.crop(box).rotate(self._correction_angle)
                    image.paste(rotated_block, box)
        if self.blocks_arranged_in_reverse_order:
            old_image = image.copy()
            for y in range(8):
                for x in range(8):
                    for i in range(self.cascaded):
                        image.putpixel((8 * (self.cascaded - 1) - i * 8 + x, y), old_image.getpixel((i * 8 + x, y)))

        return image
1219139
def convert_cropping(builder, layer, input_names, output_names, keras_layer):
    

    _check_data_format(keras_layer)
    # Get input and output names
    input_name, output_name = (input_names[0], output_names[0])
    is_1d = isinstance(keras_layer, _keras.layers.Cropping1D)

    cropping = keras_layer.cropping
    top = left = bottom = right = 0
    if is_1d:
        if type(cropping) is int:
            left = right = cropping
        elif type(cropping) is tuple:
            if type(cropping[0]) is int:
                left, right = cropping
            elif type(cropping[0]) is tuple and len(cropping[0]) == 2:
                left, right = cropping[0]
            else:
                raise ValueError("Unrecognized cropping option: %s" % (str(cropping)))
        else:
            raise ValueError("Unrecognized cropping option: %s" % (str(cropping)))
    else:
        if type(cropping) is int:
            top = left = bottom = right = cropping
        elif type(cropping) is tuple:
            if type(cropping[0]) is int:
                top, left = cropping
                bottom, right = cropping
            elif type(cropping[0]) is tuple:
                top, bottom = cropping[0]
                left, right = cropping[1]
            else:
                raise ValueError("Unrecognized cropping option: %s" % (str(cropping)))
        else:
            raise ValueError("Unrecognized cropping option: %s" % (str(cropping)))

    # Now add the layer
    builder.add_crop(name = layer,
        left = left, right=right, top=top, bottom=bottom, offset = [0,0],
        input_names = [input_name], output_name=output_name
        )
846521
def image_augmentation(images, do_colors=False, crop_size=None):
  """"""
  if crop_size is None:
    crop_size = [299, 299]
  images = tf.random_crop(images, crop_size + [3])
  images = tf.image.random_flip_left_right(images)
  if do_colors:  # More augmentation, but might be slow.
    images = tf.image.random_brightness(images, max_delta=32. / 255.)
    images = tf.image.random_saturation(images, lower=0.5, upper=1.5)
    images = tf.image.random_hue(images, max_delta=0.2)
    images = tf.image.random_contrast(images, lower=0.5, upper=1.5)
  return images
502492
def convert_cropping(builder, layer, input_names, output_names, keras_layer):
    
    # Get input and output names
    input_name, output_name = (input_names[0], output_names[0])

    if isinstance(keras_layer, keras.layers.convolutional.Cropping1D):
        left, right = keras_layer.cropping
        top, bottom = (0, 0)
    else: # 2D
        left, right = keras_layer.cropping[0]
        top, bottom = keras_layer.cropping[1]

    # Now add the layer
    builder.add_crop(name = layer,
        left = left, right=right, top=top, bottom=bottom, offset = [0,0],
        input_names = [input_name], output_name=output_name
        )
307121
def transpose(self, name=None):
    """"""
    if name is None:
      name = self.module_name + "_transpose"
    return BatchReshape(shape=lambda: self.input_shape,
                        preserve_dims=self._preserve_dims,
                        name=name)
522218
def _resize(image, width, height, crop):
    
    ext = os.path.splitext(image.name)[1].strip(".")

    with Image(file=image, format=ext) as b_image:
        # Account for orientation
        if ORIENTATION_TYPES.index(b_image.orientation) > 4:
            # Flip
            target_aspect = float(width) / float(height)
            aspect = float(b_image.height) / float(b_image.width)
        else:
            target_aspect = float(width) / float(height)
            aspect = float(b_image.width) / float(b_image.height)

        # Fix rotation
        b_image.auto_orient()

        # Calculate target size
        target_aspect = float(width) / float(height)
        aspect = float(b_image.width) / float(b_image.height)

        if ((target_aspect > aspect and not crop) or
                (target_aspect <= aspect and crop)):
            # target is wider than image, set height as maximum
            target_height = height

            # calculate width
            # -  iw / ih = tw / th (keep aspect)
            # => th ( iw / ih ) = tw
            target_width = float(target_height) * aspect

            if crop:
                # calculate crop coords
                # -  ( tw - w ) / 2
                target_left = (float(target_width) - float(width)) / 2
                target_left = int(round(target_left))
                target_top = 0

            # correct floating point error, and convert to int, round in the
            # direction of the requested width
            if width >= target_width:
                target_width = int(math.ceil(target_width))
            else:
                target_width = int(math.floor(target_width))
        else:
            # image is wider than target, set width as maximum
            target_width = width

            # calculate height
            # -  iw / ih = tw / th (keep aspect)
            # => tw / ( iw / ih ) = th
            target_height = float(target_width) / aspect

            if crop:
                # calculate crop coords
                # -  ( th - h ) / 2
                target_top = (float(target_height) - float(height)) / 2
                target_top = int(round(target_top))
                target_left = 0

            # correct floating point error and convert to int
            if height >= target_height:
                target_height = int(math.ceil(target_height))
            else:
                target_height = int(math.floor(target_height))

        # strip color profiles
        b_image.strip()

        # Resize
        b_image.resize(target_width, target_height)

        if crop:
            # Crop to target
            b_image.crop(left=target_left, top=target_top, width=width,
                         height=height)

        # Save to temporary file
        temp_file = tempfile.TemporaryFile()
        b_image.save(file=temp_file)
        # Rewind the file
        temp_file.seek(0)
        return temp_file
619853
def _crop_box(self, size):
        
        (left, top) = self.offset
        right = left + min(size[0], self.width)
        bottom = top + min(size[1], self.height)

        return (left, top, right, bottom)
997389
function cropHorizontally( img ) {
  var zoom = this.height / img.height;
  var x = 0;
  if( this.cropping == 'body' ) {
    x = 0.5 * (this.width - img.width * zoom);
  }
  else if( this.cropping == 'tail' ) {
    x = this.width - img.width * zoom;
  }
  draw.call( this, img, x, 0, zoom );
}
465876
def _do_crop(self, lines, width, height, x_crop, y_crop):
        '''
        '''
        lines = crop_or_expand(
            lines, height, default=[self.fillchar * width],
            scheme=self._schemes[y_crop])
        for i, line in enumerate(lines):
            lines[i] = crop_or_expand(
                line, width, default=self.fillchar,
                scheme=self._schemes[x_crop])
        return lines
909301
def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5):
    ""
    rows,cols = tis2hw(size)
    row_pct,col_pct = _minus_epsilon(row_pct,col_pct)
    row = int((x.size(1)-rows+1) * row_pct)
    col = int((x.size(2)-cols+1) * col_pct)
    return x[:, row:row+rows, col:col+cols].contiguous()
113290
function() {

  var b = test_batch;
  var k = Math.floor(Math.random()*num_samples_per_batch);
  var n = b*num_samples_per_batch+k;

  var p = img_data[b].data;
  var x = new convnetjs.Vol(image_dimension,image_dimension,image_channels,0.0);
  var W = image_dimension*image_dimension;
  var j=0;
  for(var dc=0;dc<image_channels;dc++) {
    var i=0;
    for(var xc=0;xc<image_dimension;xc++) {
      for(var yc=0;yc<image_dimension;yc++) {
        var ix = ((W * k) + i) * 4 + dc;
        x.set(yc,xc,dc,p[ix]/255.0-0.5);
        i++;
      }
    }
  }

  // distort position and maybe flip
  var xs = [];
  
  if (random_flip || random_position){
    for(var k=0;k<6;k++) {
      var test_variation = x;
      if(random_position){
        var dx = Math.floor(Math.random()*5-2);
        var dy = Math.floor(Math.random()*5-2);
        test_variation = convnetjs.augment(test_variation, image_dimension, dx, dy, false);
      }
      
      if(random_flip){
        test_variation = convnetjs.augment(test_variation, image_dimension, 0, 0, Math.random()<0.5); 
      }

      xs.push(test_variation);
    }
  }else{
    xs.push(x, image_dimension, 0, 0, false); // push an un-augmented copy
  }
  
  // return multiple augmentations, and we will average the network over them
  // to increase performance
  return {x:xs, label:labels[n]};
}
90814
def batchify(data, batch_size):
    """"""
    nbatch = data.shape[0] // batch_size
    data = data[:nbatch * batch_size]
    data = data.reshape((batch_size, nbatch)).T
    return data
1210371
def _random_crop_proposal(self, label, height, width):
        """"""
        from math import sqrt

        if not self.enabled or height <= 0 or width <= 0:
            return ()
        min_area = self.area_range[0] * height * width
        max_area = self.area_range[1] * height * width
        for _ in range(self.max_attempts):
            ratio = random.uniform(*self.aspect_ratio_range)
            if ratio <= 0:
                continue
            h = int(round(sqrt(min_area / ratio)))
            max_h = int(round(sqrt(max_area / ratio)))
            if round(max_h * ratio) > width:
                # find smallest max_h satifying round(max_h * ratio) <= width
                max_h = int((width + 0.4999999) / ratio)
            if max_h > height:
                max_h = height
            if h > max_h:
                h = max_h
            if h < max_h:
                # generate random h in range [h, max_h]
                h = random.randint(h, max_h)
            w = int(round(h * ratio))
            assert w <= width

            # trying to fix rounding problems
            area = w * h
            if area < min_area:
                h += 1
                w = int(round(h * ratio))
                area = w * h
            if area > max_area:
                h -= 1
                w = int(round(h * ratio))
                area = w * h
            if not (min_area <= area <= max_area and 0 <= w <= width and 0 <= h <= height):
                continue

            y = random.randint(0, max(0, height - h))
            x = random.randint(0, max(0, width - w))
            if self._check_satisfy_constraints(label, x, y, x + w, y + h, width, height):
                new_label = self._update_labels(label, (x, y, w, h), height, width)
                if new_label is not None:
                    return (x, y, w, h, new_label)
        return ()
793088
def cropped(self, t0, t1):
        """"""
        return Line(self.point(t0), self.point(t1))
281546
def flip(self):
        '''
        
        '''
        tmp = self.A.xyz
        self.A = self.B
        self.B = tmp