标签:ret sobel算子 连接 imshow size open import alt mamicode
rt
import cv2 import numpy as np path = "_lo.png" img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = gray / 255.0 #像素值0-1之间 #sobel算子分别求出gx,gy gx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3) gy = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3) mag, ang = cv2.cartToPolar(gx, gy, angleInDegrees=1) #得到梯度幅度和梯度角度阵列 g = np.zeros(gray.shape) #g与图片大小相同 #行扫描,间隔k时,进行填充,填充值为1 def edge_connection(img, size, k): for i in range(size): Yi = np.where(img[i, :] > 0) if len(Yi[0]) >= 10: #可调整 for j in range(0, len(Yi[0])-1): if Yi[0][j+1] - Yi[0][j] <= k: img[i, Yi[0][j]:Yi[0][j+1]] = 1 return img #选取边缘,提取边缘坐标,将g中相应坐标像素值设为1 X, Y = np.where((mag > np.max(mag) * 0.3)&(ang >= 0)&(ang <= 90)) g[X, Y] = 1 #边缘连接,此过程只涉及水平,垂直边缘连接,不同角度边缘只需旋转相应角度即可 g = edge_connection(g, gray.shape[0], k=20) g = cv2.rotate(g, 0) g = edge_connection(g, gray.shape[1], k=20) g = cv2.rotate(g, 2) cv2.imshow("img", img) cv2.imshow("g", g) cv2.waitKey(0)
为了看起来方便,原图手动扣了部分
标签:ret sobel算子 连接 imshow size open import alt mamicode
原文地址:https://www.cnblogs.com/er-gou-zi/p/11993945.html