我要感谢你们所有人。特别是@Yves Daoust,您为我指明了正确的方向。我想为那些面临类似问题的人分享我的解决方案:
我的解决方案使用了intersections。如果我能找到一个矩形和一个圆之间的交集区域,我也许可以将一个像素视为一个矩形,而圆显然就是圆。
两个形状的交集:
为此,您可以使用匀称:
使用points and adds some buffer (radius) to it:
from shapely.geometry import Point
circle = Point(centerx, centery).buffer(r)
创建一个形状匀称的矩形提供box:
from shapely.geometry import box
rect = box(minx=min_x, miny=min_y, maxx=max_x, maxy=max_y)
人们可以计算每个形状(从技术上讲是多边形)的许多属性,例如面积和边界点。
from shapely.geometry import Point
circle = Point(centerx, centery).buffer(r)
print(circle.area)
可以计算两个多边形的交集,它会返回一个多边形:
from shapely.geometry import Point, box
circle = Point(centerx, centery).buffer(r)
rect = box(minx=min_x, miny=min_y, maxx=max_x, maxy=max_y)
intersection = circle.intersection(rect)
像素是边长为 1 个单位(像素)的正方形。所以一个像素和任何其他形状的交集区域会产生一个值[0, 1],这就是我们要寻找的。p>
代码
请注意我使用了椭圆而不是圆形,因为它包含在内。
我的包裹:
from __future__ import annotations
from typing import Union, Tuple
from shapely.geometry import Point, Polygon, box
from shapely.affinity import scale, rotate
from matplotlib.patches import Ellipse
import numpy as np
class Pixel:
def __init__(self, x: int, y: int) -> None:
"""
Creates a 1x1 box object on the given coordinates
:param x: int
x coordinate
:param y: int
y coordinate
"""
self.x = x
self.y = y
self.body = self.__generate()
def __str__(self) -> str:
return f"Pixel(x={self.x}, y={self.y})"
def __repr__(self) -> str:
return self.__str__()
def __generate(self) -> Polygon:
"""returns a 1x1 box on self.x, self.y"""
return box(minx=self.x, miny=self.y, maxx=self.x + 1, maxy=self.y + 1)
class EllipticalMask:
def __init__(self, center: Tuple[Union[float, int], Union[float, int]],
a: Union[float, int], b: Union[float, int], angle: Union[float, int] = 0) -> None:
"""
Creates an ellipse object on the given coordinates and is able to calculate a mask with given pixels.
:param center: tuple
(x, y) coordinates
:param a: float or int
sami-major axis of ellipse
:param b: float or int
sami-minor axis of ellipse
:param angle: float or int
angle of ellipse (counterclockwise)
"""
self.center = center
self.a = a
self.b = b
self.angle = angle
self.body = self.__generate()
def __generate(self) -> Polygon:
"""Returns an ellipse with given parameters"""
return rotate(
scale(
Point(self.center[1], self.center[0]).buffer(1),
self.a,
self.b
),
self.angle
)
def __extreme_points(self) -> dict:
"""Finds extreme points which the polygon lying in"""
x, y = self.body.exterior.coords.xy
return {
"X": {
"MIN": np.floor(min(x)), "MAX": np.ceil(max(x))
},
"Y": {
"MIN": np.floor(min(y)), "MAX": np.ceil(max(y))
}
}
def __intersepter_pixels(self) -> list:
"""Creates a list of pixel objects which ellipse is covering"""
points = self.__extreme_points()
return [
Pixel(x, y)
for x in np.arange(points["X"]["MIN"], points["X"]["MAX"] + 1).astype(int)
for y in np.arange(points["Y"]["MIN"], points["Y"]["MAX"] + 1).astype(int)
if x >= 0 and y >= 0
]
def mask(self, shape: tuple) -> np.ndarray:
"""
Returns a float mask
:param shape: tuple
the shape of the mask as (width, height)
:return: ndarray
"""
pixels = self.__intersepter_pixels()
mask = np.zeros(shape).astype(float)
for pixel in pixels:
ratio = pixel.body.intersection(self.body).area
mask[pixel.x][pixel.y] = ratio
return mask
def matplotlib_artist(self) -> Ellipse:
"""
Returns a matplotlib artist
:return: Ellipse
"""
e = Ellipse(xy=(self.center[0] - 0.5, self.center[1] - 0.5), width=2 * self.a, height=2 * self.b,
angle=90 - self.angle)
e.set_facecolor('none')
e.set_edgecolor("red")
return e
class CircularMask(EllipticalMask):
def __init__(self, center: Tuple[Union[float, int], Union[float, int]],
r: Union[float, int]) -> None:
"""
Uses ellipse to create a circle
:param center: tuple
(x, y) coordinates
:param r: float or int
radius of circle
"""
super(CircularMask, self).__init__(center, r, r, 0)
用法:
from myLib import EllipticalMask
from matplotlib import pyplot as plt
m = EllipticalMask((50, 50), 25, 15, 20)
mask = m.mask((100, 100))
e = m.matplotlib_artist()
fig, ax = plt.subplots(1, 1, figsize=(4, 4))
ax.imshow(mask)
ax.add_artist(e)
plt.show()
结果:
感谢任何反馈。