Python实现实现Canny及及Hough算法代码实例解析算法代码实例解析
任务说明:编写一个钱币定位系统,其不仅能够检测出输入图像中各个钱币的边缘,同时,还能给出各个钱币的圆心坐标与半径。
效果
代码实现
Canny边缘检测:
# Author: Ji Qiu (BUPT)
# filename: my_canny.py
import cv2
import numpy as np
class Canny:
def __init__(self, Guassian_kernal_size, img, HT_high_threshold, HT_low_threshold):
'''
:param Guassian_kernal_size: 高斯滤波器尺寸
:param img: 输入的图片,在算法过程中改变
:param HT_high_threshold: 滞后阈值法中的高阈值
:param HT_low_threshold: 滞后阈值法中的低阈值
'''
self.Guassian_kernal_size = Guassian_kernal_size
self.img = img
self.y, self.x = img.shape[0:2] self.angle = np.zeros([self.y, self.x])
self.img_origin = None
self.x_kernal = np.array([[-1, 1]])
self.y_kernal = np.array([[-1], [1]])
self.HT_high_threshold = HT_high_threshold
self.HT_low_threshold = HT_low_threshold
def Get_gradient_img(self):
'''
计算梯度图和梯度方向矩阵。
:return: 生成的梯度图
'''
print ('Get_gradient_img')
new_img_x = np.zeros([self.y, self.x], dtype=np.float)
new_img_y = np.zeros([self.y, self.x], dtype=np.float)
for i in range(0, self.x):
for j in range(0, self.y):
if j == 0:
new_img_y[j][i] = 1
else:
new_img_y[j][i] = np.sum(np.array([[self.img[j - 1][i]], [self.img[j][i]]]) * self.y_kernal)
if i == 0:
new_img_x[j][i] = 1
else:
new_img_x[j][i] = np.sum(np.array([self.img[j][i - 1], self.img[j][i]]) * self.x_kernal)
gradient_img, self.angle = cv2.cartToPolar(new_img_x, new_img_y)#返回幅值和相位
self.angle = np.tan(self.angle)
self.img = gradient_img.astype(np.uint8)
return self.img
def Non_maximum_suppression (self):
'''
对生成的梯度图进行非极大化抑制,将tan值的大小与正负结合,确定离散中梯度的方向。
:return: 生成的非极大化抑制结果图
'''
print ('Non_maximum_suppression')
result = np.zeros([self.y, self.x])
评论0