opencv学习之边缘检测
Edge Detection is a critical环节 in the image processing workflow. In the realms of computer vision and machine learning, edge detection is particularly effective for feature extraction and feature detection. OpenCV offers a diverse array of edge detection algorithms, and below, I will introduce the API functions for the most commonly used ones.
Results described in this article can be viewed at:Edge Detection
Content Outline
Convert to Grayscale
Adaptive Threshold Processing
Sobel Operator
Scharr Operator
Laplacian Operator
Canny Edge Detection
Sobel Operator Combined with Laplacian Operator
Convert to Grayscale
OpenCV provides a color space conversion function, where cv.COLOR_RGB2GRAY is highly frequent, serving as the foundation for other operations. Color space conversion functions:
cv.cvtColor (src, dst, code, dstCn = 0)
- src: Original image
- dst: Output image
- code: Color space conversion code; for grayscale, use cv.COLOR_RGB2GRAY
- dstcn: Number of image channels
const src = cv.imread(img); // Read image data
const dst = new cv.Mat(); // Output image
cv.cvtColor(src, dst, cv.COLOR_RGB2GRAY, 0); // Convert to grayscale
cv.imshow(canvas, dst);
src.delete();
dst.delete();
Adaptive Threshold Processing
The adaptive threshold processing method calculates the weighted average of the surrounding area of each pixel to determine the threshold, and then uses this threshold to process the current pixel. The adaptive threshold processing function is:
cv.adaptiveThreshold(src, dst, maxValue, adaptiveMethod, thresholdType)
- maxValue: Maximum value to be processed
- adaptiveMethod: Adaptive threshold algorithm, options include cv.ADAPTIVE_THRESH_GAUSSIAN_C (Gaussian equation) or cv.ADAPTIVE_THRESH_MEAN_C (weighted average)
- thresholdType: Threshold processing method, options include cv.THRESH_BINARY (binary) or cv.THRESH_BINARY_INV (binary inversion)
const src = cv.imread(img);
const dst = new cv.Mat();
cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY, 0); // Convert to grayscale
cv.adaptiveThreshold(src, dst, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 5, 7); // Adaptive threshold processing
cv.imshow(canvas, dst); // Display output image
Effect shown:






