Abhishek Gola commited on
Commit
f70c427
·
1 Parent(s): 7cd2671

Added dexined model to space

Browse files
Files changed (3) hide show
  1. app.py +27 -0
  2. dexined.py +50 -0
  3. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2 as cv
2
+ import gradio as gr
3
+ from dexined import Dexined
4
+ from huggingface_hub import hf_hub_download
5
+
6
+ # Download ONNX model from Hugging Face
7
+ model_path = hf_hub_download(repo_id="opencv/edge_detection_dexined", filename="edge_detection_dexined_2024sep.onnx")
8
+
9
+ # Initialize model
10
+ model = Dexined(modelPath=model_path)
11
+
12
+ def detect_edges(input_image):
13
+ result = model.infer(input_image)
14
+ return result
15
+
16
+ # Gradio UI
17
+ demo = gr.Interface(
18
+ fn=detect_edges,
19
+ inputs=gr.Image(type="numpy", label="Upload Image"),
20
+ outputs=gr.Image(type="numpy", label="Output"),
21
+ title="Edge Detection DexiNed (OpenCV DNN)",
22
+ allow_flagging="never",
23
+ description="Upload an image to detect edges using OpenCV's ONNX-based edge detection using DexiNed model."
24
+ )
25
+
26
+ if __name__ == "__main__":
27
+ demo.launch()
dexined.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2 as cv
2
+ import numpy as np
3
+
4
+ class Dexined:
5
+ def __init__(self, modelPath='edge_detection_dexined_2024sep.onnx', backendId=0, targetId=0):
6
+ self._modelPath = modelPath
7
+ self._backendId = backendId
8
+ self._targetId = targetId
9
+
10
+ # Load the model
11
+ self._model = cv.dnn.readNetFromONNX(self._modelPath)
12
+ self.setBackendAndTarget(self._backendId, self._targetId)
13
+
14
+ @property
15
+ def name(self):
16
+ return self.__class__.__name__
17
+
18
+ def setBackendAndTarget(self, backendId, targetId):
19
+ self._backendId = backendId
20
+ self._targetId = targetId
21
+ self._model.setPreferableBackend(self._backendId)
22
+ self._model.setPreferableTarget(self._targetId)
23
+
24
+ @staticmethod
25
+ def sigmoid(x):
26
+ return 1.0 / (1.0 + np.exp(-x))
27
+
28
+ def postProcessing(self, output, shape):
29
+ h, w = shape
30
+ preds = []
31
+ for p in output:
32
+ img = self.sigmoid(p)
33
+ img = np.squeeze(img)
34
+ img = cv.normalize(img, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)
35
+ img = cv.resize(img, (w, h))
36
+ preds.append(img)
37
+ fuse = preds[-1]
38
+ ave = np.array(preds, dtype=np.float32)
39
+ ave = np.uint8(np.mean(ave, axis=0))
40
+ return fuse, ave
41
+
42
+ def infer(self, image):
43
+ inp = cv.dnn.blobFromImage(image, 1.0, (512, 512), (103.5, 116.2, 123.6), swapRB=False, crop=False)
44
+ self._model.setInput(inp)
45
+
46
+ # Forward pass through the model
47
+ out = self._model.forward()
48
+ result, _ = self.postProcessing(out, image.shape[:2])
49
+
50
+ return result
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ opencv-python
2
+ gradio
3
+ numpy
4
+ huggingface_hub