python - 如何在 matplotlib 中使用自定义影线填充多边形?

标签 python image matplotlib polygons hatchstyle

我正在使用 python 和 matplotlib 创建多个闭合多边形。然后我需要用阴影填充它们,这可以通过 set_hatch 完成。

http://matplotlib.org/api/artist_api.html#matplotlib.patches.Patch.set_hatch

http://matplotlib.org/examples/pylab_examples/hatch_demo.html

不幸的是,我正在处理灰度图像,我需要比默认提供的更多的影线 - 我更愿意提供可以平铺的位图(或一些类似的图像),而不是使用这些具有不同密度的影线。

我对其他 python 库(pyglet、pygame、PIL 等)持开放态度,但我更喜欢使用 python 的解决方案。

最佳答案

您可以子类化 matplotlib.hatch.Shapes 并根据单位正方形 [[-0.5, 0.5] x [-0.5, 0.5]] 内绘制的任何引用路径定义自定义影线。

暂定:

import numpy as np
import matplotlib.hatch
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon


house_path = Polygon(
    [[-0.3, -0.4], [0.3, -0.4], [0.3, 0.1], [0., 0.4], [-0.3, 0.1]],
    closed=True, fill=False).get_path()

class CustomHatch(matplotlib.hatch.Shapes):
    """
    Custom hatches defined by a path drawn inside [-0.5, 0.5] square.
    Identifier 'c'.
    """
    filled = True
    size = 1.0
    path = house_path

    def __init__(self, hatch, density):
        self.num_rows = (hatch.count('c')) * density
        self.shape_vertices = self.path.vertices
        self.shape_codes = self.path.codes
        matplotlib.hatch.Shapes.__init__(self, hatch, density)

matplotlib.hatch._hatch_types.append(CustomHatch)

fig = plt.figure()
ax = fig.add_subplot(111)

ellipse = ax.add_patch(Ellipse((0.5, 0.5), 0.3, 0.5, fill=False))
ellipse.set_hatch('c')
ellipse.set_color('red')
plt.show()

给予:

enter image description here

关于python - 如何在 matplotlib 中使用自定义影线填充多边形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17285154/

相关文章:

python - 如何在我的Mapper和Reducer中使用此代码?我想在Google集群中运行此代码

python - Blender:如何从 python 脚本移动相机

ios - iOS 中的可变图像类型?

image - 视频文件到 flutter 中的图像流

python - 如何将绘制的线保持在补丁下?

python - Python 中的特殊字符模式匹配

python - 如果邻居相等,则合并列表成员的排序列表

java - 将 ImageIO.read 用于扩展 BufferedImage 的类

python - 如何使用 Python 的 Bokeh 向日期时间轴添加更多 x 轴刻度和标签?

python - 如何将多个图像(子图)写入一个图像