# Examples from pyvista.ImageDataFilters.crop
# ===========================================

# Load a grayscale image.
import numpy as np
import pyvista as pv
from pyvista import examples
gray_image = examples.download_yinyang()
gray_image.dimensions

# Define a custom plotting helper to show the image as pixel cells.
def image_plotter(image):
    pixel_cells = image.points_to_cells()

    pl = pv.Plotter()
    pl.add_mesh(
        pixel_cells,
        cmap='gray',
        clim=[0, 255],
        lighting=False,
        show_scalar_bar=False,
    )
    pl.view_xy()
    pl.camera.tight()
    return pl

# Plot the image for context.
image_plotter(gray_image).show()

# Crop the white border around the image using active scalars as a mask. Here we
# specify a background value of `255` to correspond to white pixels. If this was
# an RGB image, we could also specify `(255, 255, 255)` as the background value.
cropped = gray_image.crop(mask=True, background_value=255)
cropped.dimensions
image_plotter(cropped).show()

# Use `margin` instead to remove 100 and 20 pixels from each side of the x- and y-axis,
# respectively.
cropped = gray_image.crop(margin=(100, 20))
cropped.dimensions
image_plotter(cropped).show()

# Use `offset` to select a starting location for the crop (from the origin at the
# bottom-left corner) along with `dimensions` to define the crop size.
cropped = gray_image.crop(offset=(50, 20, 0), dimensions=(300, 200, 1))
cropped.dimensions
image_plotter(cropped).show()

# Use `extent` directly instead of using `dimensions` and `offset` to yield
# the same result as above.
cropped = gray_image.crop(extent=(50, 349, 20, 219, 0, 0))
cropped.extent
image_plotter(cropped).show()

# Use `factor` to crop 40% of the image. This keeps 40% of the pixels along
# each axis, and removes 60% (that is, 30% from each side).
cropped = gray_image.crop(factor=0.4)
cropped.dimensions
image_plotter(cropped).show()

# Use `normalized_bounds` to crop from 40% to 80% of the image along the x-axis, and
# from 30% to 90% of the image along the y-axis.
cropped = gray_image.crop(normalized_bounds=[0.4, 0.8, 0.3, 0.9, 0.0, 1.0])
cropped.extent
image_plotter(cropped).show()

# ----------------------------------------------------------------------
# Generated by sphinx-examples-as-code https://github.com/pyvista/sphinx-examples-as-code
