简体   繁体   中英

How to get the points that outline a shape from a matplotlib artist path in python?

I have create an ellipse as follows

x=0
y=0
ells=Ellipse(xy=(x,y), #create ellipse
             width =1, 
             height =2,
             edgecolor='b',
             fc='g',
             alpha=0.3,
             zorder=0)

I can't find out how to get reference to those points so I can directly assign them to variable. I read the docs on path, but I didn't see anything there that helped. The reason I need access to the points is that I want to apply a specific tranform to them that is more complex than I can do with the transform attribute of paths. I also tried indexing them like

ells[0] #and got
TypeError: 'Path' object does not support indexing

How do I get the points as an array?

You should use Ellipse.get_path() , and work from that Path object. Below you can find a fully working example, based on this post .

import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.path import Path
from matplotlib.patches import PathPatch

img = plt.imread("image.jpg")

fig, ax = plt.subplots(1)
ax.set_aspect('equal')

ax.imshow(img)

# Create the base ellipse
ellipse = Ellipse((300, 300), width=400, height=100,
                  edgecolor='white', facecolor='none', linewidth=2)

# Get the path
path = ellipse.get_path()
# Get the list of path codes
codes = path.codes
# Get the list of path vertices
vertices = path.vertices.copy()
# Transform the vertices so that they have the correct coordinates
vertices = ellipse.get_patch_transform().transform(vertices)

# Do your transforms here
vertices[0] = vertices[0] - 10

# Create a new Path
modified_path = Path(vertices, codes)
# Create a new PathPatch
modified_ellipse = PathPatch(modified_path, edgecolor='white',
                             facecolor='none', linewidth=2)

# Add the modified ellipse
ax.add_patch(modified_ellipse)

plt.show()

Results before and after modifying the ellipse:

之前

在此处输入图片说明

My example only moves one vertice, but you can apply any transform you want. If you change the number of vertices, however, make sure to update codes accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM