handicraft_editor / src /services /image_processor.py
Deepika-05's picture
Update src/services/image_processor.py
8b0004e verified
Raw
History Blame Contribute Delete
1.1 kB
import cv2
import numpy as np
def skeletonize_image(img):
"""Reduces binary edge contours to clean, single-pixel-wide lines safely."""
# Ensure image is strictly binary (black and white)
if len(img.shape) == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# Use a structured thinning approach that won't completely eat fine details
size = np.size(binary)
skel = np.zeros(binary.shape, np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
temp_img = binary.copy()
done = False
while not done:
eroded = cv2.erode(temp_img, element)
temp = cv2.dilate(eroded, element)
temp = cv2.subtract(temp_img, temp)
skel = cv2.bitwise_or(skel, temp)
temp_img = eroded.copy()
if cv2.countNonZero(temp_img) == 0:
done = True
# Post-process: Apply a slight median blur to remove isolated pixel noise
# that causes bad path traces in SVGs
skel = cv2.medianBlur(skel, 3)
return skel