Here's Python code that detects line intersections in an image and creates a new image with the separated lines:
python
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import skeletonize
from scipy.spatial.distance import cdist
def process_image(image_path, output_path):
# Load image and convert to grayscale
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Threshold to get binary image
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# Skeletonize to get thin lines
skeleton = skeletonize(binary > 0)
skeleton = skeleton.astype(np.uint8) * 255
# Find contours
contours, _ = cv2.findContours(skeleton, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
# Create blank image for output
output = np.zeros_like(img)
# Find intersection points
intersection_points = []
for y in range(1, skeleton.shape[0]-1):
for x in range(1, skeleton.shape[1]-1):
if skeleton[y, x] == 255:
# Check 8-neighborhood
neighbors = np.sum(skeleton[y-1:y+2, x-1:x+2] > 0) - 1
if neighbors > 2: # More than 2 neighbors = intersection
intersection_points.append((x, y))
# Draw lines with different colors
colors = np.random.randint(0, 255, (len(contours), 3))
# For each contour, break at intersection points
for i, contour in enumerate(contours):
points = contour.reshape(-1, 2)
segments = []
current_segment = []
for point in points:
x, y = point
current_segment.append((x, y))
# Check if this point is an intersection
is_intersection = False
for ix, iy in intersection_points:
if abs(x - ix) <= 1 and abs(y - iy) <= 1:
is_intersection = True
break
if is_intersection and len(current_segment) > 1:
segments.append(current_segment)
current_segment = [(x, y)]
if len(current_segment) > 1:
segments.append(current_segment)
# Draw each segment with a different color
for j, segment in enumerate(segments):
color = colors[(i + j) % len(colors)].tolist()
for k in range(len(segment) - 1):
pt1 = segment[k]
pt2 = segment[k + 1]
cv2.line(output, pt1, pt2, color, 2)
# Save the output image
cv2.imwrite(output_path, output)
return output
# Example usage
if __name__ == "__main__":
input_image = "input.jpg" # Replace with your input image path
output_image = "output.jpg" # Output image path
result = process_image(input_image, output_image)
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.imshow(cv2.imread(input_image)[:,:,::-1])
plt.title("Original Image")
plt.subplot(122)
plt.imshow(result[:,:,::-1])
plt.title("Separated Lines")
plt.show()
Would you like me to explain or break down this code?