形状描边修复

This commit is contained in:
2025-12-13 20:22:13 +08:00
parent 1f887aeaf6
commit 5e01e086f2
2 changed files with 9 additions and 18 deletions

View File

@ -1191,6 +1191,10 @@ class ImageFilterImplement:
# 创建描边图像
stroke_img = np.zeros_like(img)
# 如果没有轮廓,直接返回原图
if not expanded_contours[0].any():
return image
cv2.fillPoly(stroke_img, expanded_contours, ColorHandle.parse_color(stroke_color) + (255,))
# 轮廓图像转为PIL格式

View File

@ -9,37 +9,24 @@ def fix_with_shapely(contours: list) -> np.ndarray:
"""
使用Shapely库处理复杂自相交
"""
fixed_results = []
fixed_polygons = []
for contour in contours:
# 转换输入为正确的格式
contour_array = contour.reshape(-1, 2)
# 转换为Shapely多边形
polygon = Polygon(contour_array)
# 修复自相交
if not polygon.is_valid:
polygon = polygon.buffer(0) # 修复无效多边形
# 提取修复后的轮廓点
if polygon.geom_type == 'Polygon':
fixed_points = np.array(polygon.exterior.coords, dtype=np.int32)
elif polygon.geom_type == 'MultiPolygon':
# 处理多个多边形
largest = max(polygon.geoms, key=lambda p: p.area)
fixed_points = np.array(largest.exterior.coords, dtype=np.int32)
fixed_results.append(fixed_points.reshape(-1, 1, 2))
polygon = polygon.buffer(0)
fixed_polygons.append(polygon)
# 接下来把所有轮廓合并为一个
if len(fixed_results) > 1:
merged_polygon = unary_union([Polygon(cnt.reshape(-1, 2)) for cnt in fixed_results])
if len(fixed_polygons) >= 1:
merged_polygon = unary_union(fixed_polygons)
if merged_polygon.geom_type == 'Polygon':
merged_points = np.array(merged_polygon.exterior.coords, dtype=np.int32)
elif merged_polygon.geom_type == 'MultiPolygon':
largest = max(merged_polygon.geoms, key=lambda p: p.area)
merged_points = np.array(largest.exterior.coords, dtype=np.int32)
return [merged_points.reshape(-1, 1, 2)]
elif len(fixed_results) == 1:
return [fixed_results[0]]
else:
logger.warning("No valid contours found after fixing with Shapely.")
return [np.array([], dtype=np.int32).reshape(0, 1, 2)]