Проблема, которую вы описываете, довольно распространенная при работе с извлечением контуров по цвету. Вот несколько подходов для решения:
Подход 1: Использование иерархии контуров
import cv2
import numpy as np
from shapely.geometry import Polygon
from shapely.ops import unary_union
def extract_color_polygons_with_holes(image, target_colors, tolerance=10):
polygons_by_color = {}
for color_name, target_color in target_colors.items():
# Создаем маску для цвета
lower = np.array([max(0, c - tolerance) for c in target_color])
upper = np.array([min(255, c + tolerance) for c in target_color])
mask = cv2.inRange(image, lower, upper)
# Находим контуры с иерархией
contours, hierarchy = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
if hierarchy is not None:
polygons = []
for i, contour in enumerate(contours):
if len(contour) >= 3: # Минимум 3 точки для полигона
# Упрощаем контур
epsilon = 0.02 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
if len(approx) >= 3:
points = approx.reshape(-1, 2)
try:
poly = Polygon(points)
if poly.is_valid and poly.area > 10: # Фильтруем мелкие полигоны
# Проверяем, является ли это внешним контуром
if hierarchy[0][i][3] == -1: # Нет родителя = внешний контур
polygons.append(poly)
except:
continue
polygons_by_color[color_name] = polygons
return polygons_by_color
Подход 2: Вычитание пересекающихся областей
def extract_exclusive_color_polygons(image, target_colors, tolerance=10):
masks = {}
polygons_by_color = {}
# Создаем маски для всех цветов
for color_name, target_color in target_colors.items():
lower = np.array([max(0, c - tolerance) for c in target_color])
upper = np.array([min(255, c + tolerance) for c in target_color])
masks[color_name] = cv2.inRange(image, lower, upper)
# Для каждого цвета вычитаем области других цветов
for color_name, mask in masks.items():
# Создаем маску исключений (все остальные цвета)
exclusion_mask = np.zeros_like(mask)
for other_color, other_mask in masks.items():
if other_color != color_name:
exclusion_mask = cv2.bitwise_or(exclusion_mask, other_mask)
# Вычитаем пересекающиеся области
clean_mask = cv2.bitwise_and(mask, cv2.bitwise_not(exclusion_mask))
# Находим контуры
contours, _ = cv2.findContours(clean_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
polygons = []
for contour in contours:
if len(contour) >= 3:
epsilon = 0.02 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
if len(approx) >= 3:
points = approx.reshape(-1, 2)
try:
poly = Polygon(points)
if poly.is_valid and poly.area > 10:
polygons.append(poly)
except:
continue
polygons_by_color[color_name] = polygons
return polygons_by_color
Подход 3: С использованием морфологических операций
def extract_color_polygons_morphology(image, target_colors, tolerance=10):
polygons_by_color = {}
for color_name, target_color in target_colors.items():
# Создаем маску
lower = np.array([max(0, c - tolerance) for c in target_color])
upper = np.array([min(255, c + tolerance) for c in target_color])
mask = cv2.inRange(image, lower, upper)
# Морфологические операции для очистки
kernel = np.ones((3,3), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
# Находим контуры
contours, hierarchy = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
polygons = []
if hierarchy is not None:
for i, contour in enumerate(contours):
# Работаем только с внешними контурами
if hierarchy[0][i][3] == -1 and len(contour) >= 3:
epsilon = 0.01 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
if len(approx) >= 3:
points = approx.reshape(-1, 2)
try:
poly = Polygon(points)
if poly.is_valid and poly.area > 50:
polygons.append(poly)
except:
continue
polygons_by_color[color_name] = polygons
return polygons_by_color
Пример использования
# Загружаем изображение
image = cv2.imread('your_image.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Определяем целевые цвета (RGB)
target_colors = {
'red': [255, 0, 0],
'blue': [0, 0, 255],
'green': [0, 255, 0]
}
# Извлекаем полигоны
polygons = extract_exclusive_color_polygons(image, target_colors, tolerance=20)
# Визуализация результата
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 8))
ax.imshow(image)
colors_plot = {'red': 'red', 'blue': 'blue', 'green': 'green'}
for color_name, polys in polygons.items():
for poly in polys:
x, y = poly.exterior.xy
ax.plot(x, y, color=colors_plot[color_name], linewidth=2)
ax.fill(x, y, alpha=0.3, color=colors_plot[color_name])
plt.show()
Ключевые моменты решения:
- Подход 1 использует иерархию контуров для правильной обработки вложенных областей
- Подход 2 явно вычитает области других цветов из маски каждого цвета
- Подход 3 использует морфологические операции для очистки шума
Попробуйте второй подход - он обычно дает наиболее точные результаты для задач, где нужно избежать пересечений между цветовыми областями.