OpenCV提供了3种边沿检测算法
本文分别采用这3种算法进行边沿检测,并给出比较结果
代码如下
import numpy
import argparse
import cv2
image = cv2.imread('1.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
#if don't use a floating point data type when computing
#the gradient magnitude image, you will miss edges
lap = cv2.Laplacian(gray, cv2.CV_64F)
lap = numpy.uint8(numpy.absolute(lap))
#display two images in a figure
cv2.imshow("Edge detection by Laplacaian", numpy.hstack([lap, gray]))
cv2.imwrite("1_edge_by_laplacian.jpg", numpy.hstack([gray, lap]))
if(cv2.waitKey(0)==27):
cv2.destroyAllWindows()
代码如下
import numpy
import argparse
import cv2
image = cv2.imread('1.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1)
sobelx = numpy.uint8(numpy.absolute(sobelx))
sobely = numpy.uint8(numpy.absolute(sobely))
sobelcombine = cv2.bitwise_or(sobelx,sobely)
#display two images in a figure
cv2.imshow("Edge detection by Sobel", numpy.hstack([gray,sobelx,sobely, sobelcombine]))
cv2.imwrite("1_edge_by_sobel.jpg", numpy.hstack([gray,sobelx,sobely, sobelcombine]))
if(cv2.waitKey(0)==27):
cv2.destroyAllWindows()
代码如下
import numpy
import argparse
import cv2
image = cv2.imread('1.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
#30 and 150 is the threshold, larger than 150 is considered as edge,
#less than 30 is considered as not edge
canny = cv2.Canny(gray, 30, 150)
canny = numpy.uint8(numpy.absolute(canny))
#display two images in a figure
cv2.imshow("Edge detection by Canny", numpy.hstack([gray,canny]))
cv2.imwrite("1_edge_by_canny.jpg", numpy.hstack([gray,canny]))
if(cv2.waitKey(0)==27):
cv2.destroyAllWindows()
以下是3种边沿检测算法的处理结果。 从图中可以看出,Lapacian的检测效果最差,Canny的最明显,因为该算法将边沿检测结果进行了二值化处理。Sobel的检测结果也是较好的,从图中可以看到边沿检测结果是较为清晰的。