多种变换实现图像检测处理并输出写入文件。
001、自定义函数hough变换
Hough_transform.py文件
函数源码:
#filename _rename_as_Hough_transform
import numpy as np
import math
class Hough_transform:
def __init__(self, img, angle, step=5, threshold=135):
'''
:param img: 输入的图像
:param angle: 输入的梯度方向矩阵
:param step: Hough 变换步长大小
:param threshold: 筛选单元的阈值
'''
self.img = img
self.angle = angle
self.y, self.x = img.shape[0:2]
self.radius = math.ceil( math.sqrt( self.y ** 2 + self.x ** 2 ) )
self.step = step
self.vote_matrix = np.zeros(
[math.ceil( self.y / self.step ), math.ceil( self.x / self.step ), math.ceil( self.radius / self.step )] )
self.threshold = threshold
self.circles = []
def Hough_transform_algorithm(self):
'''
按照 x,y,radius 建立三维空间,根据图片中边上的点沿梯度方向对空间中的所有单
元进行投票。每个点投出来结果为一折线。
:return: 投票矩阵
'''
print( 'Hough_transform_algorithm' )
for i in range( 1, self.y - 1 ):
for j in range( 1, self.x - 1 ):
if self.img[i][j] > 0:
y = i
x = j
r = 0
while y < self.y and x < self.x and y >= 0 and x >= 0:
self.vote_matrix[math.floor( y / self.step )][math.floor( x / self.step )][
math.floor( r / self.step )] += 1
y = y + self.step * self.angle[i][j]
x = x + self.step
r = r + math.sqrt( (self.step * self.angle[i][j]) ** 2 + self.step ** 2 )
y = i - self.step * self.angle[i][j]
x = j - self.step
r = math.sqrt( (self.step * self.angle[i][j]) ** 2 + self.step ** 2 )
while y < self.y and x < self.x and y >= 0 and x >= 0:
self.vote_matrix[math.floor( y / self.step )][math.floor( x / self.step )][
math.floor( r / self.step )] += 1
y = y - self.step * self.angle[i][j]
x = x - self.step
r = r + math.sqrt( (self.step * self.angle[i][j]) ** 2 + self.step ** 2 )
return self.vote_matrix
def Select_Circle(self):
'''
按照阈值从投票矩阵中筛选出合适的圆,并作极大化抑制,这里的非极大化抑制我采
用的是邻近点结果取平均值的方法,而非单纯的取极大值。
:return: None
'''
print( 'Select_Circle' )
houxuanyuan = []
for i in range( 0, math.ceil( self.y / self.step ) ):
for j in range( 0, math.ceil( self.x / self.step ) ):
for r in range( 0, math.ceil( self.radius / self.step ) ):
if self.vote_matrix