不使用opencv库用python编写对于应用了非最大抑制技术后的图像采取双阈值方法确定边缘代码
时间: 2023-05-20 16:04:10 浏览: 43
以下是一个使用Python编写的双阈值方法确定边缘的代码示例,该代码不使用OpenCV库:
```python
import numpy as np
from PIL import Image
def non_max_suppression(img, D):
M, N = img.shape
Z = np.zeros((M,N), dtype=np.int32)
angle = D * 180. / np.pi
angle[angle < 0] += 180
for i in range(1,M-1):
for j in range(1,N-1):
q = 255
r = 255
# angle 0
if (0 <= angle[i,j] < 22.5) or (157.5 <= angle[i,j] <= 180):
q = img[i, j+1]
r = img[i, j-1]
# angle 45
elif (22.5 <= angle[i,j] < 67.5):
q = img[i+1, j-1]
r = img[i-1, j+1]
# angle 90
elif (67.5 <= angle[i,j] < 112.5):
q = img[i+1, j]
r = img[i-1, j]
# angle 135
elif (112.5 <= angle[i,j] < 157.5):
q = img[i-1, j-1]
r = img[i+1, j+1]
if (img[i,j] >= q) and (img[i,j] >= r):
Z[i,j] = img[i,j]
else:
Z[i,j] = 0
return Z
def threshold(img, lowThresholdRatio=0.05, highThresholdRatio=0.09):
highThreshold = img.max() * highThresholdRatio
lowThreshold = highThreshold * lowThresholdRatio
M, N = img.shape
res = np.zeros((M,N), dtype=np.int32)
weak = np.int32(25)
strong = np.int32(255)
strong_i, strong_j = np.where(img >= highThreshold)
zeros_i, zeros_j = np.where(img < lowThreshold)
weak_i, weak_j = np.where((img <= highThreshold) & (img >= lowThreshold))
res[strong_i, strong_j] = strong
res[weak_i, weak_j] = weak
return (res, weak, strong)
def hysteresis(img, weak, strong=255):
M, N = img.shape
for i in range(1, M-1):
for j in range(1, N-1):
if (img[i,j] == weak):
if ((img[i+1, j-1] == strong) or (img[i+1, j] == strong) or (img[i+1, j+1] == strong)
or (img[i, j-1] == strong) or (img[i, j+1] == strong)
or (img[i-1, j-1] == strong) or (img[i-1, j] == strong) or (img[i-1, j+1] == strong)):
img[i, j] = strong
else:
img[i, j] = 0
return img
def canny_edge_detection(img, sigma=1.4, kernel_size=5, lowThresholdRatio=0.05, highThresholdRatio=0.09):
# Gaussian blur
img_smoothed = np.zeros(img.shape)
gaussian_kernel = np.zeros((kernel_size, kernel_size))
for i in range(kernel_size):
for j in range(kernel_size):
gaussian_kernel[i, j] = (1/(2*np.pi*(sigma**2)))*np.exp(-(((i-(kernel_size//2))**2)+((j-(kernel_size//2))**2))/(2*(sigma**2)))
img_smoothed = convolve(img, gaussian_kernel)
# Gradient
Gx = np.zeros(img_smoothed.shape)
Gy = np.zeros(img_smoothed.shape)
for i in range(1, img_smoothed.shape[0]-1):
for j in range(1, img_smoothed.shape[1]-1):
Gx[i, j] = img_smoothed[i, j+1] - img_smoothed[i, j-1]
Gy[i, j] = img_smoothed[i-1, j] - img_smoothed[i+1, j]
G = np.sqrt(np.square(Gx) + np.square(Gy))
D = np.arctan2(Gy, Gx)
# Non-maximum suppression
img_suppressed = non_max_suppression(G, D)
# Double thresholding
img_thresholded, weak, strong = threshold(img_suppressed, lowThresholdRatio, highThresholdRatio)
# Hysteresis
img_hysteresis = hysteresis(img_thresholded, weak, strong)
return img_hysteresis
# Example usage
img = np.array(Image.open('image.jpg').convert('L'))
canny_img = canny_edge_detection(img)
Image.fromarray(canny_img).show()
```
请注意,此代码仅用于演示目的,可能需要进行优化和调整以适应您的特定用例。