gpt4 book ai didi

python - 填充多边形外部 |索引超出圆形边界的掩码数组?

转载 作者:太空狗 更新时间:2023-10-29 17:45:39 24 4
gpt4 key购买 nike

我使用 plot(x,y,'r') 绘制一个红色圆圈。 x 和 y 是这样的数组,当作为 (x,y) 配对并绘制时,所有点形成一条圆线。

fill(x,y,'r') 绘制一个用红色填充(或着色)的红色圆圈。

如何让圆圈内部保持白色,但在圆圈外部填充到轴边界?

我研究过使用 fill_between(x_array, y1_array, y2_array, where) 但在试用了一下之后,我认为它不适用于我的 x,y 数组。我想 fill_between() 在圆外,在由轴边界定义的正方形内,但我不认为 fill_between() 有能力……我我确信我可以将它变成一个整数类型的问题,其中 delta x 和 delta y 将变为零,但我不愿意。

如果有人看到我在 fill_between() 中遗漏了什么,请告诉我。

我真正需要做的就是屏蔽掉位于由 x 和 y 创建的圆的边界之外的二维数组中的数字,这样当二维数组被视为内部的彩色图或轮廓时圆圈是图像,外面是白色的。

这可以通过二维阵列的掩蔽技术来实现吗?就像使用 masked_where() 一样?我还没有调查过,但会的。

有什么想法吗?谢谢

编辑 1:这是我有权展示的内容,我认为可以解释我的问题。

from pylab import *
from matplotlib.path import Path
from matplotlib.patches import PathPatch

f=Figure()
a=f.add_subplot(111)

# x,y,z are 2d arrays

# sometimes i plot a color plot
# im = a.pcolor(x,y,z)
a.pcolor(x,y,z)

# sometimes i plot a contour
a.contour(x,y,z)

# sometimes i plot both using a.hold(True)

# here is the masking part.
# sometimes i just want to see the boundary drawn without masking
# sometimes i want to see the boundary drawn with masking inside of the boundary
# sometimes i want to see the boundary drawn with masking outside of the boundary

# depending on the vectors that define x_bound and y_bound, sometimes the boundary
# is a circle, sometimes it is not.

path=Path(vpath)
patch=PathPatch(path,facecolor='none')
a.add_patch(patch) # just plots boundary if anything has been previously plotted on a
if ('I want to mask inside'):
patch.set_facecolor('white') # masks(whitens) inside if pcolor is currently on a,
# but if contour is on a, the contour part is not whitened out.
else: # i want to mask outside
im.set_clip_path(patch) # masks outside only when im = a.pcolor(x,y,z)
# the following commands don't update any masking but they don't produce errors?
# patch.set_clip_on(True)
# a.set_clip_on(True)
# a.set_clip_path(patch)

a.show()

最佳答案

All I am really needing to do is mask out numbers in a 2d array that are located beyond this boundary of the circle created with x and y, such that when the 2D array is viewed as a color plot, or contour, inside the circle will be the image, and outside will be white-ed out.

你有两个选择:

首先,您可以为图像使用掩码数组。这更复杂,但更安全。要屏蔽圆外的阵列,从中心点生成距离图,并屏蔽距离大于半径的位置。

更简单的选择是在绘制图像后使用 im.set_clip_path() 剪切补丁之外的区域。

参见 this example from the matplotlib gallery .不幸的是,根据我的经验,对于某些轴(非笛卡尔轴),这可能有点小问题。不过,在所有其他情况下,它应该都能完美运行。

编辑:顺便说一句,this is how to do what you originally asked :绘制一个内部有孔的多边形。不过,如果您只想遮盖图像,最好选择上述两个选项之一。

Edit2:只是举一个简单的例子来说明这两种方式......

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

def main():
# Generate some random data
nx, ny = 100, 100
data = np.random.random((ny,nx))

# Define a circle in the center of the data with a radius of 20 pixels
radius = 20
center_x = nx // 2
center_y = ny // 2

plot_masked(data, center_x, center_y, radius)
plot_clipped(data, center_x, center_y, radius)
plt.show()

def plot_masked(data, center_x, center_y, radius):
"""Plots the image masked outside of a circle using masked arrays"""
# Calculate the distance from the center of the circle
ny, nx = data.shape
ix, iy = np.meshgrid(np.arange(nx), np.arange(ny))
distance = np.sqrt((ix - center_x)**2 + (iy - center_y)**2)

# Mask portions of the data array outside of the circle
data = np.ma.masked_where(distance > radius, data)

# Plot
plt.figure()
plt.imshow(data)
plt.title('Masked Array')

def plot_clipped(data, center_x, center_y, radius):
"""Plots the image clipped outside of a circle by using a clip path"""
fig = plt.figure()
ax = fig.add_subplot(111)

# Make a circle
circ = patches.Circle((center_x, center_y), radius, facecolor='none')
ax.add_patch(circ) # Plot the outline

# Plot the clipped image
im = ax.imshow(data, clip_path=circ, clip_on=True)

plt.title('Clipped Array')

main()

enter image description here enter image description here

编辑 2:在原始图上绘制 mask 多边形:这里有一些关于如何绘制一个多边形的更多细节,该多边形在当前绘图上掩盖了它之外的所有内容。显然,没有更好的方法来裁剪等高线图(无论如何我都能找到...)。

import numpy as np
import matplotlib.pyplot as plt

def main():
# Contour some regular (fake) data
grid = np.arange(100).reshape((10,10))
plt.contourf(grid)

# Verticies of the clipping polygon in counter-clockwise order
# (A triange, in this case)
poly_verts = [(2, 2), (5, 2.5), (6, 8), (2, 2)]

mask_outside_polygon(poly_verts)

plt.show()

def mask_outside_polygon(poly_verts, ax=None):
"""
Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that
all areas outside of the polygon specified by "poly_verts" are masked.

"poly_verts" must be a list of tuples of the verticies in the polygon in
counter-clockwise order.

Returns the matplotlib.patches.PathPatch instance plotted on the figure.
"""
import matplotlib.patches as mpatches
import matplotlib.path as mpath

if ax is None:
ax = plt.gca()

# Get current plot limits
xlim = ax.get_xlim()
ylim = ax.get_ylim()

# Verticies of the plot boundaries in clockwise order
bound_verts = [(xlim[0], ylim[0]), (xlim[0], ylim[1]),
(xlim[1], ylim[1]), (xlim[1], ylim[0]),
(xlim[0], ylim[0])]

# A series of codes (1 and 2) to tell matplotlib whether to draw a line or
# move the "pen" (So that there's no connecting line)
bound_codes = [mpath.Path.MOVETO] + (len(bound_verts) - 1) * [mpath.Path.LINETO]
poly_codes = [mpath.Path.MOVETO] + (len(poly_verts) - 1) * [mpath.Path.LINETO]

# Plot the masking patch
path = mpath.Path(bound_verts + poly_verts, bound_codes + poly_codes)
patch = mpatches.PathPatch(path, facecolor='white', edgecolor='none')
patch = ax.add_patch(patch)

# Reset the plot limits to their original extents
ax.set_xlim(xlim)
ax.set_ylim(ylim)

return patch

if __name__ == '__main__':
main()

Clipped contour plot

关于python - 填充多边形外部 |索引超出圆形边界的掩码数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3320311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com