File size: 2,515 Bytes
3673b9e
856189d
 
a6a05ca
 
 
d7ff44b
a6a05ca
d7ff44b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6a05ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import gradio as gr
import cv2
import numpy as np
from flask import Flask, render_template

# A placeholder function; Actual LiveWire code would be much more involved
#def live_wire_segmentation(image, points):
    # This is a placeholder. Implement actual live wire segmentation here.
#    return image


import cv2
import numpy as np

def compute_cost(image):
    gradient_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
    gradient_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)
    gradient_magnitude = cv2.magnitude(gradient_x, gradient_y)
    return gradient_magnitude

def dijkstra(cost, start, end):
    # Dimensions of the image
    h, w = cost.shape
    visited = np.zeros((h, w), dtype=np.bool_)
    distance = np.full((h, w), np.inf)
    parent = np.zeros((h, w, 2), dtype=np.int16)  # to store the path
    
    distance[start[1], start[0]] = 0
    for _ in range(h * w):
        min_distance = np.inf
        for y in range(h):
            for x in range(w):
                if not visited[y, x] and distance[y, x] < min_distance:
                    u = (x, y)
                    min_distance = distance[y, x]
        
        visited[u[1], u[0]] = True
        
        # Check neighbors
        for i in [-1, 0, 1]:
            for j in [-1, 0, 1]:
                if 0 <= u[1] + i < h and 0 <= u[0] + j < w:
                    v = (u[0] + j, u[1] + i)
                    alt = distance[u[1], u[0]] + cost[v[1], v[0]]
                    if alt < distance[v[1], v[0]]:
                        distance[v[1], v[0]] = alt
                        parent[v[1], v[0]] = u

    # Reconstruct path from end to start by following parents
    path = []
    while end != start:
        path.append(end)
        end = tuple(parent[end[1], end[0]])
    path.append(start)
    
    return path

def live_wire_segmentation(image, start, end):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cost = compute_cost(gray)
    path = dijkstra(cost, start, end)
    
    for point in path:
        cv2.circle(image, point, 1, (0, 255, 0), -1)  # Draw path on the image
    
    return image

def main_app():
    interface = gr.Interface(
        fn=live_wire_segmentation,
        inputs=["image", gr.inputs.Sketchpad()],  # You may have to adjust this for latest version of Gradio
        outputs="image",
        live=True
    )
    interface.launch()

app = Flask(__name__)

@app.route('/')
def index():
    main_app()
    return "Gradio App Running!"

if __name__ == "__main__":
    app.run(debug=True)