1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| import cv2 import math import numpy as np import scipy.ndimage
def orientated_non_max_suppression(mag, ang): ang_quant = np.round(ang / (np.pi/4)) % 4 winE = np.array([[0, 0, 0],[1, 1, 1], [0, 0, 0]]) winSE = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) winS = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]]) winSW = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
magE = non_max_suppression(mag, winE) magSE = non_max_suppression(mag, winSE) magS = non_max_suppression(mag, winS) magSW = non_max_suppression(mag, winSW)
mag[ang_quant == 0] = magE[ang_quant == 0] mag[ang_quant == 1] = magSE[ang_quant == 1] mag[ang_quant == 2] = magS[ang_quant == 2] mag[ang_quant == 3] = magSW[ang_quant == 3] return mag
def non_max_suppression(data, win): data_max = scipy.ndimage.filters.maximum_filter(data, footprint=win, mode='constant') data_max[data != data_max] = 0 return data_max
gray_image = cv2.imread(r'rr2.png', 0)
with_nmsup = True fudgefactor = 1.3 sigma = 21 kernel = 2*math.ceil(2*sigma)+1
gray_image = gray_image/255.0 blur = cv2.GaussianBlur(gray_image, (kernel, kernel), sigma) gray_image = cv2.subtract(gray_image, blur)
sobelx = cv2.Sobel(gray_image, cv2.CV_64F, 1, 0, ksize=3) sobely = cv2.Sobel(gray_image, cv2.CV_64F, 0, 1, ksize=3) mag = np.hypot(sobelx, sobely) ang = np.arctan2(sobely, sobelx)
threshold = 4 * fudgefactor * np.mean(mag) mag[mag < threshold] = 0
if with_nmsup is False: mag = cv2.normalize(mag, 0, 255, cv2.NORM_MINMAX) kernel = np.ones((5,5),np.uint8) result = cv2.morphologyEx(mag, cv2.MORPH_CLOSE, kernel) cv2.imshow('im', result) cv2.waitKey()
else:
mag = orientated_non_max_suppression(mag, ang) mag[mag > 0] = 255 mag = mag.astype(np.uint8)
kernel = np.ones((5,5),np.uint8) result = cv2.morphologyEx(mag, cv2.MORPH_CLOSE, kernel)
cv2.imwrite("result.png", result) cv2.waitKey()
|