samples/python/snippets/laplace.py#
An example using Laplace filter for edge detection in python
1#!/usr/bin/env python
2
3'''
4 This program demonstrates Laplace point/edge detection using
5 OpenCV function Laplacian()
6 It captures from the camera of your choice: 0, 1, ... default 0
7 Usage:
8 python laplace.py <ddepth> <smoothType> <sigma>
9 If no arguments given default arguments will be used.
10
11 Keyboard Shortcuts:
12 Press space bar to exit the program.
13 '''
14
15# Python 2/3 compatibility
16from __future__ import print_function
17
18import numpy as np
19import cv2 as cv
20import sys
21
22def main():
23 # Declare the variables we are going to use
24 ddepth = cv.CV_16S
25 smoothType = "MedianBlur"
26 sigma = 3
27 if len(sys.argv)==4:
28 ddepth = sys.argv[1]
29 smoothType = sys.argv[2]
30 sigma = sys.argv[3]
31 # Taking input from the camera
32 cap=cv.VideoCapture(0)
33 # Create Window and Trackbar
34 cv.namedWindow("Laplace of Image", cv.WINDOW_AUTOSIZE)
35 cv.createTrackbar("Kernel Size Bar", "Laplace of Image", sigma, 15, lambda x:x)
36 # Printing frame width, height and FPS
37 print("=="*40)
38 print("Frame Width: ", cap.get(cv.CAP_PROP_FRAME_WIDTH), "Frame Height: ", cap.get(cv.CAP_PROP_FRAME_HEIGHT), "FPS: ", cap.get(cv.CAP_PROP_FPS))
39 while True:
40 # Reading input from the camera
41 ret, frame = cap.read()
42 if ret == False:
43 print("Can't open camera/video stream")
44 break
45 # Taking input/position from the trackbar
46 sigma = cv.getTrackbarPos("Kernel Size Bar", "Laplace of Image")
47 # Setting kernel size
48 ksize = (sigma*5)|1
49 # Removing noise by blurring with a filter
50 if smoothType == "GAUSSIAN":
51 smoothed = cv.GaussianBlur(frame, (ksize, ksize), sigma, sigma)
52 if smoothType == "BLUR":
53 smoothed = cv.blur(frame, (ksize, ksize))
54 if smoothType == "MedianBlur":
55 smoothed = cv.medianBlur(frame, ksize)
56
57 # Apply Laplace function
58 laplace = cv.Laplacian(smoothed, ddepth, 5)
59 # Converting back to uint8
60 result = cv.convertScaleAbs(laplace, (sigma+1)*0.25)
61 # Display Output
62 cv.imshow("Laplace of Image", result)
63 k = cv.waitKey(30)
64 if k == 27:
65 return
66if __name__ == "__main__":
67 print(__doc__)
68 main()
69 cv.destroyAllWindows()