Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/edge_detection.py
16337 views
1
import cv2 as cv
2
import argparse
3
4
parser = argparse.ArgumentParser(
5
description='This sample shows how to define custom OpenCV deep learning layers in Python. '
6
'Holistically-Nested Edge Detection (https://arxiv.org/abs/1504.06375) neural network '
7
'is used as an example model. Find a pre-trained model at https://github.com/s9xie/hed.')
8
parser.add_argument('--input', help='Path to image or video. Skip to capture frames from camera')
9
parser.add_argument('--prototxt', help='Path to deploy.prototxt', required=True)
10
parser.add_argument('--caffemodel', help='Path to hed_pretrained_bsds.caffemodel', required=True)
11
parser.add_argument('--width', help='Resize input image to a specific width', default=500, type=int)
12
parser.add_argument('--height', help='Resize input image to a specific height', default=500, type=int)
13
args = parser.parse_args()
14
15
#! [CropLayer]
16
class CropLayer(object):
17
def __init__(self, params, blobs):
18
self.xstart = 0
19
self.xend = 0
20
self.ystart = 0
21
self.yend = 0
22
23
# Our layer receives two inputs. We need to crop the first input blob
24
# to match a shape of the second one (keeping batch size and number of channels)
25
def getMemoryShapes(self, inputs):
26
inputShape, targetShape = inputs[0], inputs[1]
27
batchSize, numChannels = inputShape[0], inputShape[1]
28
height, width = targetShape[2], targetShape[3]
29
30
self.ystart = (inputShape[2] - targetShape[2]) / 2
31
self.xstart = (inputShape[3] - targetShape[3]) / 2
32
self.yend = self.ystart + height
33
self.xend = self.xstart + width
34
35
return [[batchSize, numChannels, height, width]]
36
37
def forward(self, inputs):
38
return [inputs[0][:,:,self.ystart:self.yend,self.xstart:self.xend]]
39
#! [CropLayer]
40
41
#! [Register]
42
cv.dnn_registerLayer('Crop', CropLayer)
43
#! [Register]
44
45
# Load the model.
46
net = cv.dnn.readNet(args.prototxt, args.caffemodel)
47
48
kWinName = 'Holistically-Nested Edge Detection'
49
cv.namedWindow('Input', cv.WINDOW_NORMAL)
50
cv.namedWindow(kWinName, cv.WINDOW_NORMAL)
51
52
cap = cv.VideoCapture(args.input if args.input else 0)
53
while cv.waitKey(1) < 0:
54
hasFrame, frame = cap.read()
55
if not hasFrame:
56
cv.waitKey()
57
break
58
59
cv.imshow('Input', frame)
60
61
inp = cv.dnn.blobFromImage(frame, scalefactor=1.0, size=(args.width, args.height),
62
mean=(104.00698793, 116.66876762, 122.67891434),
63
swapRB=False, crop=False)
64
net.setInput(inp)
65
66
out = net.forward()
67
out = out[0, 0]
68
out = cv.resize(out, (frame.shape[1], frame.shape[0]))
69
cv.imshow(kWinName, out)
70
71