Skip to content

Instantly share code, notes, and snippets.

@creotiv
Created April 22, 2024 08:58
Show Gist options
  • Save creotiv/06acfa52597cb09b0eae45b88e0f63ad to your computer and use it in GitHub Desktop.
Save creotiv/06acfa52597cb09b0eae45b88e0f63ad to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
import svgwrite
def find_and_vectorize_edges(image_path, K):
# Шаг 1: Уменьшение количества цветов
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
Z = img.reshape((-1, 3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
_, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
reduced_img = res.reshape((img.shape))
# Шаг 2: Обнаружение границ
edges = cv2.Canny(cv2.cvtColor(reduced_img, cv2.COLOR_RGB2GRAY), 50, 150)
# Шаг 3: Нахождение контуров и создание SVG
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
dwg = svgwrite.Drawing('vectorized_image.svg', profile='tiny')
# Аппроксимация контуров и запись в SVG
for cnt in contours:
epsilon = 0.02 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
points = ['{},{}'.format(point[0][0], point[0][1]) for point in approx]
polyline = dwg.polyline(points=points, stroke='black', fill='none')
dwg.add(polyline)
dwg.save()
return dwg.tostring()
# Путь к изображению и количество цветов
image_path = 'path_to_your_image.jpg'
K = 8
# Генерация SVG
svg_output = find_and_vectorize_edges(image_path, K)
print(svg_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment