# Examples from pyvista.ImageDataFilters.reslice
# ==============================================

# Rotate a photograph about its own center.
import numpy as np
import pyvista as pv
from pyvista import examples
gourds = examples.download_gourds()
center = np.array(gourds.center)
rotate = pv.Transform().translate(-center).rotate_z(45).translate(center)

# Reslice the image onto its own grid through that rotation. The picture turns
# but the samples do not move, so the output is still axis-aligned and the
# corners the rotation vacated hold `background_value`.
rotated = gourds.reslice(
    gourds, 'linear', transform=rotate, background_value=0
)

# `transform()` cannot do this. It would turn
# the grid along with the picture, leaving an image whose samples no longer
# line up with the axes.
pl = pv.Plotter()
_ = pl.add_mesh(rotated, rgba=True, lighting=False)
pl.view_xy()
pl.camera.tight()
pl.show()

# Create a small image whose values are the `x` coordinate of each point.
import numpy as np
import pyvista as pv
image = pv.ImageData(dimensions=(6, 6, 1))
image['values'] = image.points[:, 0]
image.bounds

# Create a reference image which covers part of it with half the spacing.
reference = pv.ImageData(
    dimensions=(6, 6, 1), spacing=(0.5, 0.5, 1.0), origin=(2.0, 1.0, 0.0)
)

# Reslice the image onto the reference.
resliced = image.reslice(reference, 'linear')

# The output has the reference's geometry.
resliced.dimensions
resliced.origin

# Since the image is sampled at the reference's points, the values still equal the
# `x` coordinate of the points they are stored at.
bool(np.allclose(resliced['values'], resliced.points[:, 0]))

# Give the reference a rotated `direction_matrix` to sample
# an oblique plane. The output carries that orientation, and its values still sit at
# the `x` coordinate they name.
oblique = pv.ImageData(dimensions=(3, 3, 1), origin=(1.0, 1.0, 0.0))
oblique.direction_matrix = pv.Transform().rotate_z(30).matrix[:3, :3]
resliced = image.reslice(oblique, 'linear')
bool(np.allclose(resliced.direction_matrix, oblique.direction_matrix))
bool(np.allclose(resliced['values'], resliced.points[:, 0]))

# Reference points outside the image are filled with `background_value`. This
# reference samples at `x = 2, 4, 6, 8`, and the image ends at `x = 5`.
reference = pv.ImageData(
    dimensions=(4, 1, 1), spacing=(2.0, 1.0, 1.0), origin=(2.0, 0.0, 0.0)
)
resliced = image.reslice(reference, 'linear', background_value=-1.0)
resliced['values'].tolist()

# Pass a `transform` to move the image before it is sampled. Shifting it two
# along `x` brings two more of its values within reach of the same reference.
shift = pv.Transform().translate((2, 0, 0))
resliced = image.reslice(
    reference, 'linear', transform=shift, background_value=-1.0
)
resliced['values'].tolist()

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