Crops an image in the center.

    Parameters
    ----------
    size : tuple, (height, width)
        Finally size after cropping.
345110
def crop(im, size):
    
    diff = [im.shape[index] - size[index] for index in (0, 1)]
    im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
    return im2
706345
def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
    
    assert isinstance(crop_size, int), crop_size
    boxes = tf.stop_gradient(boxes)

    # TF's crop_and_resize produces zeros on border
    if pad_border:
        # this can be quite slow
        image = tf.pad(image, [[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC')
        boxes = boxes + 1

    @under_name_scope()
    def transform_fpcoor_for_tf(boxes, image_shape, crop_shape):
        """
        The way tf.image.crop_and_resize works (with normalized box):
        Initial point (the value of output[0]): x0_box * (W_img - 1)
        Spacing: w_box * (W_img - 1) / (W_crop - 1)
        Use the above grid to bilinear sample.

        However, what we want is (with fpcoor box):
        Spacing: w_box / W_crop
        Initial point: x0_box + spacing/2 - 0.5
        (-0.5 because bilinear sample (in my definition) assumes floating point coordinate
         (0.0, 0.0) is the same as pixel value (0, 0))

        This function transform fpcoor boxes to a format to be used by tf.image.crop_and_resize

        Returns:
            y1x1y2x2
        """
        x0, y0, x1, y1 = tf.split(boxes, 4, axis=1)

        spacing_w = (x1 - x0) / tf.cast(crop_shape[1], tf.float32)
        spacing_h = (y1 - y0) / tf.cast(crop_shape[0], tf.float32)

        imshape = [tf.cast(image_shape[0] - 1, tf.float32), tf.cast(image_shape[1] - 1, tf.float32)]
        nx0 = (x0 + spacing_w / 2 - 0.5) / imshape[1]
        ny0 = (y0 + spacing_h / 2 - 0.5) / imshape[0]

        nw = spacing_w * tf.cast(crop_shape[1] - 1, tf.float32) / imshape[1]
        nh = spacing_h * tf.cast(crop_shape[0] - 1, tf.float32) / imshape[0]

        return tf.concat([ny0, nx0, ny0 + nh, nx0 + nw], axis=1)

    # Expand bbox to a minium size of 1
    # boxes_x1y1, boxes_x2y2 = tf.split(boxes, 2, axis=1)
    # boxes_wh = boxes_x2y2 - boxes_x1y1
    # boxes_center = tf.reshape((boxes_x2y2 + boxes_x1y1) * 0.5, [-1, 2])
    # boxes_newwh = tf.maximum(boxes_wh, 1.)
    # boxes_x1y1new = boxes_center - boxes_newwh * 0.5
    # boxes_x2y2new = boxes_center + boxes_newwh * 0.5
    # boxes = tf.concat([boxes_x1y1new, boxes_x2y2new], axis=1)

    image_shape = tf.shape(image)[2:]
    boxes = transform_fpcoor_for_tf(boxes, image_shape, [crop_size, crop_size])
    image = tf.transpose(image, [0, 2, 3, 1])   # nhwc
    ret = tf.image.crop_and_resize(
        image, boxes, tf.cast(box_ind, tf.int32),
        crop_size=[crop_size, crop_size])
    ret = tf.transpose(ret, [0, 3, 1, 2])   # ncss
    return ret
791826
def dilate(self, size):
        
        if size > 0:
            from scipy.ndimage.morphology import binary_dilation
            size = (size * 2) + 1
            coords = self.coordinates
            tmp = zeros(self.extent + size * 2)
            coords = (coords - self.bbox[0:len(self.center)] + size)
            tmp[coords.T.tolist()] = 1
            tmp = binary_dilation(tmp, ones((size, size)))
            new = asarray(where(tmp)).T + self.bbox[0:len(self.center)] - size
            new = [c for c in new if all(c >= 0)]
        else:
            return self
        
        return one(new)
1164500
public void setImageSize(Point size) {
		Assert.isNotNull(size);
		Assert.isTrue(size.x >= 0 && size.y >= 0);
		fSize = size;
	}
584979
def processed_image(image, options = {})
      size = options[:size]
      upsample = !!options[:upsample]

      return image unless size.present? && has_convertible_format?

      if options[:crop]
        crop(size, options[:crop_from], options[:crop_size], upsample)
      else
        resize(size, upsample)
      end
    end
82775
function crop(stream, config, cb) {
  PNGCrop.cropToStream(stream, config, function(err, outputStream) {
    var buf = concat(function(data) {
      cb(err, data);
    });
    outputStream.pipe(buf);
  });
}
510919
def fixed_crop(src, x0, y0, w, h, size=None, interpolation=cv2.INTER_CUBIC):
    """"""
    out = mx.nd.crop(src, begin=(y0, x0, 0), end=(y0+h, x0+w, int(src.shape[2])))
    if size is not None and (w, h) != size:
        out = resize(out, size, interpolation=interpolation)
    return out
88104
def crop_with_focuspoint(width = nil, height = nil)
      if self.respond_to? "resize_to_limit"
        begin
          x = model.focus_x || 0
          y = -(model.focus_y || 0)

          manipulate! do |img|
            orig_w = img['width']
            orig_h = img['height']

            ratio = width.to_f / height
            orig_ratio = orig_w.to_f / orig_h

            x_offset = 0
            y_offset = 0
            w = orig_w
            h = orig_h
            if ratio < orig_ratio
              w = orig_h * ratio

              half_w = w / 2.0
              half_orig_w = orig_w / 2.0

              x_offset = x * half_orig_w

              x_offset = (x <=> 0.0) * (half_orig_w - half_w) if x != 0 && x_offset.abs > half_orig_w - half_w
            elsif ratio > orig_ratio
              h = orig_w / ratio

              half_h = h / 2.0
              half_orig_h = orig_h / 2.0

              y_offset = y * half_orig_h

              y_offset = (y <=> 0.0) * (half_orig_h - half_h) if y != 0 && y_offset.abs > half_orig_h - half_h
            end

            img.combine_options do |op|
              op.crop "#{w.to_i}x#{h.to_i}#{'%+d' % x_offset.round}#{'%+d' % y_offset.round}"
              op.gravity 'Center'
            end
            img.resize("#{width}x#{height}")
            img
          end

        rescue Exception => e
          raise "Failed to crop - #{e.message}"
        end

      else
        raise "Failed to crop #{attachment}. Add mini_magick."
      end
    end
791220
private function crop($optimal_width, $optimal_height, $new_width, $new_height)
    {
        // Find center - this will be used for the crop
        $crop_start_x = ($optimal_width  / 2) - ($new_width  / 2);
        $crop_start_y = ($optimal_height / 2) - ($new_height / 2);

        $crop = $this->image_resized;

        $dest_offset_x = max(0, -$crop_start_x);
        $dest_offset_y = max(0, -$crop_start_y);
        $crop_start_x  = max(0, $crop_start_x);
        $crop_start_y  = max(0, $crop_start_y);
        $dest_width    = min($optimal_width, $new_width);
        $dest_height   = min($optimal_height, $new_height);

        // Now crop from center to exact requested size
        $this->image_resized = imagecreatetruecolor($new_width, $new_height);

        imagealphablending($crop, true);
        imagealphablending($this->image_resized, false);
        imagesavealpha($this->image_resized, true);

        imagefilledrectangle($this->image_resized, 0, 0, $new_width, $new_height,
            imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127)
        );

        imagecopyresampled($this->image_resized, $crop, $dest_offset_x, $dest_offset_y, $crop_start_x, $crop_start_y, $dest_width, $dest_height, $dest_width, $dest_height);

        return true;
    }
276572
def center_crop(im, min_sz=None):
    
    r,c,*_ = im.shape
    if min_sz is None: min_sz = min(r,c)
    start_r = math.ceil((r-min_sz)/2)
    start_c = math.ceil((c-min_sz)/2)
    return crop(im, start_r, start_c, min_sz)
146588
def get_thumbnail(self, original, size, crop, options):
        
        try:
            image = self.create(original, size, crop, options)
        except ThumbnailError:
            image = None
        finally:
            self.cleanup(original)
        return image
1128695
def set_size(self, size):
        
        if not isinstance(size, baseinteger):
            raise TypeError("size can only be an instance of type baseinteger")
        self._call("setSize",
                     in_p=[size])
1020742
def center_crop(dimensions, upsample)
      if is_smaller_than(dimensions) && upsample == false
        dimensions = reduce_to_image(dimensions)
      end
      image_file.thumb("#{dimensions_to_string(dimensions)}#")
    end
997993
def resize(self, size):
        
        count = max(int(size), 0) - len(self)

        if count == 0:
            pass
        elif -count == len(self):
            self._value = bytes()
        elif count > 0:
            self._value += b'\x00' * count
        else:
            self._value = self._value[:count]
        size = len(self)
        self._bit_size = size * 8
        self._align_to_byte_size = size
657792
def crop_centers
      logger.info 'cropping centers'
      scale_factor = @csv_file.split(/\n/).first.split(',').last.to_f
      percent = (scale_factor*100).round
      logger.debug "cropping to #{percent}%"
      unless @options[:without_cropping]
        images = Image.parse(@input_file)
        images.each do |image|
          width_offset = (image.w.to_f * (1 - scale_factor) / 2).round
          height_offset = (image.h.to_f * (1 - scale_factor) / 2).round
          logger.debug "cropping #{image.name}"
          `convert #{image.name} -crop "#{percent}%x#{percent}%+#{width_offset}+#{height_offset}" #{image.name}`
        end
      end

      # Since all images have been cropped, we need to change d,e params to move images based on how much was cropped
      # Re-run commands that have been run at this point
      logger.info 'rerunning commands'
      @new_input = 'project_converted_translation_cropped.pto'
      `match-n-shift --input #{@csv} -o project_cropped.pto`
      `pto_var --opt=TrX,TrY project_cropped.pto -o project_pto_var_cropped.pto`
      runner = Runner.new(@options.merge(input: 'project_pto_var_cropped.pto', output: @new_input))
      runner.run('convert_translation_parameters')
      `pano_modify -p 0 --fov=AUTO -o #{@new_input} #{@new_input}`

      logger.info "Read new #{@new_input}"
      # Read new input pto file
      @input_file = File.new(@new_input, 'r').read
      images = Image.parse(@input_file)
      ds = images.map(&:d).uniq.sort
      es = images.map(&:e).uniq.sort

      d_diffs = []
      ds.each_with_index do |_, i|
        next if i == 0
        d_diffs.push((ds[i] - ds[i-1]).abs * (1-scale_factor))
      end

      e_diffs = []
      es.each_with_index do |_, i|
        next if i == 0
        e_diffs.push((es[i] - es[i-1]).abs * (1-scale_factor))
      end

      d_map = Hash[ds.map.with_index { |d, i| i == 0 ? [d, d] : [d, d - d_diffs[0..(i-1)].reduce(:+)] }]
      e_map = Hash[es.map.with_index { |e, i|  i == 0 ? [e, e] : [e, e - e_diffs[0..(i-1)].reduce(:+)] }]

      d_min, d_max = d_map.values.minmax
      e_min, e_max = e_map.values.minmax
      d_offset = ((d_max - d_min) / 2.0) + d_min
      e_offset = ((e_max - e_min) / 2.0) + e_min

      logger.info 'saving new d,e values'
      @lines = @input_file.each_line.map do |line|
        image = images.find { |i| i.raw == line }
        if image
          image.d = (d_map[image.d] - d_offset).round(8).to_s
          image.e = (e_map[image.e] - e_offset).round(8).to_s
          image.to_s
        else
          next line
        end
      end.compact

      save_file
    end
246124
def get_crop_size(crop_w, crop_h, image_w, image_h):
    
    scale1 = float(crop_w) / float(image_w)
    scale2 = float(crop_h) / float(image_h)
    scale1_w = crop_w  # int(round(img_w * scale1))
    scale1_h = int(round(image_h * scale1))
    scale2_w = int(round(image_w * scale2))
    scale2_h = crop_h  # int(round(img_h * scale2))

    if scale1_h > crop_h:  # scale1_w == crop_w
        # crop on vertical
        return (scale1_w, scale1_h)
    else:  # scale2_h == crop_h and scale2_w > crop_w
        #crop on horizontal
        return (scale2_w, scale2_h)
509935
def _random_crop(image, size):
  """"""
  bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
  random_image, bbox = distorted_bounding_box_crop(
      image,
      bbox,
      min_object_covered=0.1,
      aspect_ratio_range=(3. / 4, 4. / 3.),
      area_range=(0.08, 1.0),
      max_attempts=1,
      scope=None)
  bad = _at_least_x_are_true(tf.shape(image), tf.shape(random_image), 3)

  image = tf.cond(
      bad, lambda: _center_crop(_do_scale(image, size), size),
      lambda: tf.image.resize_bicubic([random_image], [size, size])[0])
  return image