This is the 8th day of my participation in Gwen Challenge

OpenCV is a C++ library, currently popular computer vision programming library, for real-time processing of computer vision problems, it covers a lot of modules in the field of computer vision. In Python, the OpenCV library is often used for image processing.

This article shows how to implement edge detection using OpenCV in Python3 – Canny edge detection:

above

Edge detection plays a very important role in computer vision task of artificial intelligence.

Opencv provides a very convenient Canny function for edge detection. Canny edge detection is a very popular edge detection algorithm, which was proposed by John Canny in 1986.

The prototype of the Canny function in Opencv-Python is:

Edge = cv2.Canny(image, Threshold1, Threshold2 [, edges[, apertureSize[, L2gradient]]]). The first parameter is the original image to be processed. The second parameter is the threshold1; The third parameter is the threshold2.Copy the code

Canny algorithm steps

Canny edge detection algorithm consists of five main steps:

  • Gaussian filter is used to denoise the image.
  • Calculate gradient;
  • Use non-maximum suppression on the edge;
  • Use double (double) threshold to remove false positive;
  • Finally, all edges and the connections between them are analyzed to ensure true edges and eliminate edges that are not obvious.

Canny algorithm implementation code

import cv2
import numpy as np

original_img = cv2.imread("E:\\demo\\lena.jpg".0)

canny = cv2.Canny(original_img, 50.150)

cv2.imshow('original_img', original_img)
cv2.imshow('Canny', canny)

cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

The output is:

The above program is static only. The following program can adjust the threshold size at run time.

The code is as follows:

import cv2
import numpy as np

def CannyThreshold(lowThreshold):
    detected_edges = cv2.GaussianBlur(gray, (3.3), 0)
    detected_edges = cv2.Canny(detected_edges, lowThreshold, lowThreshold * ratio, apertureSize=kernel_size)
    dst = cv2.bitwise_and(img, img, mask=detected_edges) 
    cv2.imshow('canny demo', dst)

lowThreshold = 0
max_lowThreshold = 100
ratio = 3
kernel_size = 3

img = cv2.imread("E:\\demo\\lena.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.namedWindow('canny demo')
cv2.createTrackbar('Min threshold'.'canny demo', lowThreshold, max_lowThreshold, CannyThreshold)

CannyThreshold(0)

if cv2.waitKey(0) = =27:
    cv2.destroyAllWindows()
Copy the code

The output is:

A series of articles will follow this month,

Wonderful article, please pay attention.