Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7.9k
Add the ability to change the focal length of the camera for 3D plots#22046
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
6 commits Select commitHold shift + click to select a range
e8a3f57
Specify the focal length for 3d plots
scottshambaugh81f3a23
Merge branch 'main' into 3d_plot_focal_length
scottshambaughc1e5e0a
Code review changes
scottshambaughde45ae1
Merge branch 'main' into 3d_plot_focal_length
scottshambaugh7bd9bd9
More code review changes and tests
scottshambaughb0135c7
Additional code review changes
scottshambaughFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
31 changes: 31 additions & 0 deletionsdoc/users/next_whats_new/3d_plot_focal_length.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
Give the 3D camera a custom focal length | ||
---------------------------------------- | ||
Users can now better mimic real-world cameras by specifying the focal length of | ||
the virtual camera in 3D plots. The default focal length of 1 corresponds to a | ||
Field of View (FOV) of 90 deg, and is backwards-compatible with existing 3D | ||
plots. An increased focal length between 1 and infinity "flattens" the image, | ||
while a decreased focal length between 1 and 0 exaggerates the perspective and | ||
gives the image more apparent depth. | ||
The focal length can be calculated from a desired FOV via the equation: | ||
.. mathmpl:: | ||
focal\_length = 1/\tan(FOV/2) | ||
.. plot:: | ||
:include-source: true | ||
from mpl_toolkits.mplot3d import axes3d | ||
import matplotlib.pyplot as plt | ||
fig, axs = plt.subplots(1, 3, subplot_kw={'projection': '3d'}, | ||
constrained_layout=True) | ||
X, Y, Z = axes3d.get_test_data(0.05) | ||
focal_lengths = [0.25, 1, 4] | ||
for ax, fl in zip(axs, focal_lengths): | ||
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) | ||
ax.set_proj_type('persp', focal_length=fl) | ||
ax.set_title(f"focal_length = {fl}") | ||
plt.tight_layout() | ||
plt.show() |
55 changes: 55 additions & 0 deletionsexamples/mplot3d/projections.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
""" | ||
======================== | ||
3D plot projection types | ||
======================== | ||
Demonstrates the different camera projections for 3D plots, and the effects of | ||
changing the focal length for a perspective projection. Note that Matplotlib | ||
corrects for the 'zoom' effect of changing the focal length. | ||
The default focal length of 1 corresponds to a Field of View (FOV) of 90 deg. | ||
An increased focal length between 1 and infinity "flattens" the image, while a | ||
decreased focal length between 1 and 0 exaggerates the perspective and gives | ||
the image more apparent depth. In the limiting case, a focal length of | ||
infinity corresponds to an orthographic projection after correction of the | ||
zoom effect. | ||
You can calculate focal length from a FOV via the equation: | ||
.. mathmpl:: | ||
1 / \tan (FOV / 2) | ||
Or vice versa: | ||
.. mathmpl:: | ||
FOV = 2 * \atan (1 / focal length) | ||
""" | ||
scottshambaugh marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
from mpl_toolkits.mplot3d import axes3d | ||
import matplotlib.pyplot as plt | ||
fig, axs = plt.subplots(1, 3, subplot_kw={'projection': '3d'}) | ||
# Get the test data | ||
X, Y, Z = axes3d.get_test_data(0.05) | ||
# Plot the data | ||
for ax in axs: | ||
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) | ||
# Set the orthographic projection. | ||
axs[0].set_proj_type('ortho') # FOV = 0 deg | ||
axs[0].set_title("'ortho'\nfocal_length = ∞", fontsize=10) | ||
# Set the perspective projections | ||
axs[1].set_proj_type('persp') # FOV = 90 deg | ||
axs[1].set_title("'persp'\nfocal_length = 1 (default)", fontsize=10) | ||
axs[2].set_proj_type('persp', focal_length=0.2) # FOV = 157.4 deg | ||
axs[2].set_title("'persp'\nfocal_length = 0.2", fontsize=10) | ||
plt.show() |
57 changes: 46 additions & 11 deletionslib/mpl_toolkits/mplot3d/axes3d.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -57,7 +57,7 @@ class Axes3D(Axes): | ||
def __init__( | ||
self, fig, rect=None, *args, | ||
elev=30, azim=-60, roll=0, sharez=None, proj_type='persp', | ||
box_aspect=None, computed_zorder=True, focal_length=None, | ||
**kwargs): | ||
""" | ||
Parameters | ||
@@ -104,6 +104,13 @@ def __init__( | ||
This behavior is deprecated in 3.4, the default will | ||
change to False in 3.5. The keyword will be undocumented | ||
and a non-False value will be an error in 3.6. | ||
focal_length : float, default: None | ||
For a projection type of 'persp', the focal length of the virtual | ||
camera. Must be > 0. If None, defaults to 1. | ||
For a projection type of 'ortho', must be set to either None | ||
or infinity (numpy.inf). If None, defaults to infinity. | ||
The focal length can be computed from a desired Field Of View via | ||
the equation: focal_length = 1/tan(FOV/2) | ||
scottshambaugh marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
**kwargs | ||
Other optional keyword arguments: | ||
@@ -117,7 +124,7 @@ def __init__( | ||
self.initial_azim = azim | ||
self.initial_elev = elev | ||
self.initial_roll = roll | ||
self.set_proj_type(proj_type, focal_length) | ||
self.computed_zorder = computed_zorder | ||
self.xy_viewLim = Bbox.unit() | ||
@@ -989,18 +996,33 @@ def view_init(self, elev=None, azim=None, roll=None, vertical_axis="z"): | ||
dict(x=0, y=1, z=2), vertical_axis=vertical_axis | ||
) | ||
def set_proj_type(self, proj_type, focal_length=None): | ||
""" | ||
Set the projection type. | ||
Parameters | ||
---------- | ||
proj_type : {'persp', 'ortho'} | ||
The projection type. | ||
focal_length : float, default: None | ||
For a projection type of 'persp', the focal length of the virtual | ||
camera. Must be > 0. If None, defaults to 1. | ||
The focal length can be computed from a desired Field Of View via | ||
the equation: focal_length = 1/tan(FOV/2) | ||
""" | ||
_api.check_in_list(['persp', 'ortho'], proj_type=proj_type) | ||
if proj_type == 'persp': | ||
if focal_length is None: | ||
focal_length = 1 | ||
elif focal_length <= 0: | ||
raise ValueError(f"focal_length = {focal_length} must be " | ||
"greater than 0") | ||
self._focal_length = focal_length | ||
elif proj_type == 'ortho': | ||
if focal_length not in (None, np.inf): | ||
raise ValueError(f"focal_length = {focal_length} must be " | ||
f"None for proj_type = {proj_type}") | ||
scottshambaugh marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
self._focal_length = np.inf | ||
def _roll_to_vertical(self, arr): | ||
"""Roll arrays to match the different vertical axis.""" | ||
@@ -1056,8 +1078,21 @@ def get_proj(self): | ||
V = np.zeros(3) | ||
V[self._vertical_axis] = -1 if abs(elev_rad) > 0.5 * np.pi else 1 | ||
# Generate the view and projection transformation matrices | ||
if self._focal_length == np.inf: | ||
# Orthographic projection | ||
viewM = proj3d.view_transformation(eye, R, V, roll_rad) | ||
projM = proj3d.ortho_transformation(-self._dist, self._dist) | ||
else: | ||
# Perspective projection | ||
# Scale the eye dist to compensate for the focal length zoom effect | ||
eye_focal = R + self._dist * ps * self._focal_length | ||
viewM = proj3d.view_transformation(eye_focal, R, V, roll_rad) | ||
projM = proj3d.persp_transformation(-self._dist, | ||
self._dist, | ||
self._focal_length) | ||
# Combine all the transformation matrices to get the final projection | ||
M0 = np.dot(viewM, worldM) | ||
M = np.dot(projM, M0) | ||
return M | ||
@@ -1120,7 +1155,7 @@ def cla(self): | ||
pass | ||
self._autoscaleZon = True | ||
if self._focal_length == np.inf: | ||
self._zmargin = rcParams['axes.zmargin'] | ||
else: | ||
self._zmargin = 0. | ||
26 changes: 15 additions & 11 deletionslib/mpl_toolkits/mplot3d/proj3d.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong.Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 17 additions & 1 deletionlib/mpl_toolkits/tests/test_mplot3d.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.