轮廓发现
是基于图像边缘提取的基础寻找对象轮廓的方法。所以边缘提取阈值的选定会影响最终轮廓发现的结果。
利用梯度来避免阈值的烦恼
相关代码
import cv2 as cv
def edge_demo(image):
""" 边缘处理 :param image: :return: """
blurred = cv.GaussianBlur(image, (3, 3), 0)
gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
# X Gradient
xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0)
# Y Gradient
ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1)
# edge
# edge_output = cv.Canny(xgrad, ygrad, 50, 150)
edge_output = cv.Canny(gray, 30, 100)
cv.imshow("Canny Edge", edge_output)
return edge_output
def contours_demo(image):
binary = edge_demo(image)
# 查找轮廓 这里最新的返回值只有两个
contours, heriachy = cv.findContours(binary, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
# 2为绘图的线宽 可以设定为-1表示填充整个轮廓
cv.drawContours(image, contours, i, (0, 0, 255), -1)
approxCurve = cv.approxPolyDP(contour, 4, True)
if approxCurve.shape[0] > 6:
cv.drawContours(image, contours, i, (0, 255, 255), 2)
if approxCurve.shape[0] == 4:
cv.drawContours(image, contours, i, (255, 255, 0), 2)
print(approxCurve.shape[0])
print(i)
cv.imshow("detect contours", image)
src = cv.imread("main.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
contours_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()