File size: 1,101 Bytes
567f0c7
 
 
 
8b0004e
 
567f0c7
8b0004e
 
 
 
 
 
 
567f0c7
8b0004e
567f0c7
 
8b0004e
 
 
 
567f0c7
8b0004e
 
567f0c7
8b0004e
 
 
 
567f0c7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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