Python实现Canny及Hough算法代码实例解析


Posted in Python onAugust 06, 2020

任务说明:编写一个钱币定位系统,其不仅能够检测出输入图像中各个钱币的边缘,同时,还能给出各个钱币的圆心坐标与半径。

效果

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])
    for i in range(1, self.y - 1):
      for j in range(1, self.x - 1):
        if abs(self.img[i][j]) <= 4:
          result[i][j] = 0
          continue
        elif abs(self.angle[i][j]) > 1:
          gradient2 = self.img[i - 1][j]
          gradient4 = self.img[i + 1][j]
          # g1 g2
          #  C
          #  g4 g3
          if self.angle[i][j] > 0:
            gradient1 = self.img[i - 1][j - 1]
            gradient3 = self.img[i + 1][j + 1]
          #  g2 g1
          #  C
          # g3 g4
          else:
            gradient1 = self.img[i - 1][j + 1]
            gradient3 = self.img[i + 1][j - 1]
        else:
          gradient2 = self.img[i][j - 1]
          gradient4 = self.img[i][j + 1]
          # g1
          # g2 C g4
          #   g3
          if self.angle[i][j] > 0:
            gradient1 = self.img[i - 1][j - 1]
            gradient3 = self.img[i + 1][j + 1]
          #   g3
          # g2 C g4
          # g1
          else:
            gradient3 = self.img[i - 1][j + 1]
            gradient1 = self.img[i + 1][j - 1]

        temp1 = abs(self.angle[i][j]) * gradient1 + (1 - abs(self.angle[i][j])) * gradient2
        temp2 = abs(self.angle[i][j]) * gradient3 + (1 - abs(self.angle[i][j])) * gradient4
        if self.img[i][j] >= temp1 and self.img[i][j] >= temp2:
          result[i][j] = self.img[i][j]
        else:
          result[i][j] = 0
    self.img = result
    return self.img

  def Hysteresis_thresholding(self):
    '''
    对生成的非极大化抑制结果图进行滞后阈值法,用强边延伸弱边,这里的延伸方向为梯度的垂直方向,
    将比低阈值大比高阈值小的点置为高阈值大小,方向在离散点上的确定与非极大化抑制相似。
    :return: 滞后阈值法结果图
    '''
    print ('Hysteresis_thresholding')
    
    for i in range(1, self.y - 1):
      for j in range(1, self.x - 1):
        if self.img[i][j] >= self.HT_high_threshold:
          if abs(self.angle[i][j]) < 1:
            if self.img_origin[i - 1][j] > self.HT_low_threshold:
              self.img[i - 1][j] = self.HT_high_threshold
            if self.img_origin[i + 1][j] > self.HT_low_threshold:
              self.img[i + 1][j] = self.HT_high_threshold
            # g1 g2
            #  C
            #  g4 g3
            if self.angle[i][j] < 0:
              if self.img_origin[i - 1][j - 1] > self.HT_low_threshold:
                self.img[i - 1][j - 1] = self.HT_high_threshold
              if self.img_origin[i + 1][j + 1] > self.HT_low_threshold:
                self.img[i + 1][j + 1] = self.HT_high_threshold
            #  g2 g1
            #  C
            # g3 g4
            else:
              if self.img_origin[i - 1][j + 1] > self.HT_low_threshold:
                self.img[i - 1][j + 1] = self.HT_high_threshold
              if self.img_origin[i + 1][j - 1] > self.HT_low_threshold:
                self.img[i + 1][j - 1] = self.HT_high_threshold
          else:
            if self.img_origin[i][j - 1] > self.HT_low_threshold:
              self.img[i][j - 1] = self.HT_high_threshold
            if self.img_origin[i][j + 1] > self.HT_low_threshold:
              self.img[i][j + 1] = self.HT_high_threshold
            # g1
            # g2 C g4
            #   g3
            if self.angle[i][j] < 0:
              if self.img_origin[i - 1][j - 1] > self.HT_low_threshold:
                self.img[i - 1][j - 1] = self.HT_high_threshold
              if self.img_origin[i + 1][j + 1] > self.HT_low_threshold:
                self.img[i + 1][j + 1] = self.HT_high_threshold
            #   g3
            # g2 C g4
            # g1
            else:
              if self.img_origin[i - 1][j + 1] > self.HT_low_threshold:
                self.img[i + 1][j - 1] = self.HT_high_threshold
              if self.img_origin[i + 1][j - 1] > self.HT_low_threshold:
                self.img[i + 1][j - 1] = self.HT_high_threshold
    return self.img

  def canny_algorithm(self):
    '''
    按照顺序和步骤调用以上所有成员函数。
    :return: Canny 算法的结果
    '''
    self.img = cv2.GaussianBlur(self.img, (self.Guassian_kernal_size, self.Guassian_kernal_size), 0)
    self.Get_gradient_img()
    self.img_origin = self.img.copy()
    self.Non_maximum_suppression()
    self.Hysteresis_thresholding()
    return self.img

Hough变换

# Author: Ji Qiu (BUPT)
# filename: my_hough.py


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[i][j][r] >= self.threshold:
            y = i * self.step + self.step / 2
            x = j * self.step + self.step / 2
            r = r * self.step + self.step / 2
            houxuanyuan.append((math.ceil(x), math.ceil(y), math.ceil(r)))
    if len(houxuanyuan) == 0:
      print("No Circle in this threshold.")
      return
    x, y, r = houxuanyuan[0]
    possible = []
    middle = []
    for circle in houxuanyuan:
      if abs(x - circle[0]) <= 20 and abs(y - circle[1]) <= 20:
        possible.append([circle[0], circle[1], circle[2]])
      else:
        result = np.array(possible).mean(axis=0)
        middle.append((result[0], result[1], result[2]))
        possible.clear()
        x, y, r = circle
        possible.append([x, y, r])
    result = np.array(possible).mean(axis=0)
    middle.append((result[0], result[1], result[2]))

    def takeFirst(elem):
      return elem[0]

    middle.sort(key=takeFirst)
    x, y, r = middle[0]
    possible = []
    for circle in middle:
      if abs(x - circle[0]) <= 20 and abs(y - circle[1]) <= 20:
        possible.append([circle[0], circle[1], circle[2]])
      else:
        result = np.array(possible).mean(axis=0)
        print("Circle core: (%f, %f) Radius: %f" % (result[0], result[1], result[2]))
        self.circles.append((result[0], result[1], result[2]))
        possible.clear()
        x, y, r = circle
        possible.append([x, y, r])
    result = np.array(possible).mean(axis=0)
    print("Circle core: (%f, %f) Radius: %f" % (result[0], result[1], result[2]))
    self.circles.append((result[0], result[1], result[2]))
 

  def Calculate(self):
    '''
    按照算法顺序调用以上成员函数
    :return: 圆形拟合结果图,圆的坐标及半径集合
    '''
    self.Hough_transform_algorithm()
    self.Select_Circle()
    return self.circles

调用

# Author: Ji Qiu (BUPT)
# filename: main.py

import cv2
import math
from my_hough import Hough_transform
from my_canny import Canny

# np.set_printoptions(threshold=np.inf)
Path = "picture_source/picture.jpg"
Save_Path = "picture_result/"
Reduced_ratio = 2
Guassian_kernal_size = 3
HT_high_threshold = 25
HT_low_threshold = 6
Hough_transform_step = 6
Hough_transform_threshold = 110

if __name__ == '__main__':
  img_gray = cv2.imread(Path, cv2.IMREAD_GRAYSCALE)
  img_RGB = cv2.imread(Path)
  y, x = img_gray.shape[0:2]
  img_gray = cv2.resize(img_gray, (int(x / Reduced_ratio), int(y / Reduced_ratio)))
  img_RGB = cv2.resize(img_RGB, (int(x / Reduced_ratio), int(y / Reduced_ratio)))
  # canny takes about 40 seconds
  print ('Canny ...')
  canny = Canny(Guassian_kernal_size, img_gray, HT_high_threshold, HT_low_threshold)
  canny.canny_algorithm()
  cv2.imwrite(Save_Path + "canny_result.jpg", canny.img)
  
  # hough takes about 30 seconds
  print ('Hough ...')
  Hough = Hough_transform(canny.img, canny.angle, Hough_transform_step, Hough_transform_threshold)
  circles = Hough.Calculate()
  for circle in circles:
    cv2.circle(img_RGB, (math.ceil(circle[0]), math.ceil(circle[1])), math.ceil(circle[2]), (28, 36, 237), 2)
  cv2.imwrite(Save_Path + "hough_result.jpg", img_RGB)
  print ('Finished!')

运行效果

Python实现Canny及Hough算法代码实例解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
pycharm 使用心得(九)解决No Python interpreter selected的问题
Jun 06 Python
Python实现的Excel文件读写类
Jul 30 Python
Python 闭包的使用方法
Sep 07 Python
Python OpenCV 直方图的计算与显示的方法示例
Feb 08 Python
怎么使用pipenv管理你的python项目
Mar 12 Python
pycharm运行程序时在Python console窗口中运行的方法
Dec 03 Python
对python读写文件去重、RE、set的使用详解
Dec 11 Python
python3实现小球转动抽奖小游戏
Apr 15 Python
利用python求积分的实例
Jul 03 Python
在python中画正态分布图像的实例
Jul 08 Python
python2和python3实现在图片上加汉字的方法
Aug 22 Python
Python OpenCV读取中文路径图像的方法
Jul 02 Python
vscode调试django项目的方法
Aug 06 #Python
Python如何使用input函数获取输入
Aug 06 #Python
Python map及filter函数使用方法解析
Aug 06 #Python
python学习笔记之多进程
Aug 06 #Python
Selenium alert 弹窗处理的示例代码
Aug 06 #Python
Python如何进行时间处理
Aug 06 #Python
Python学习笔记之装饰器
Aug 06 #Python
You might like
如何提高MYSQL数据库的查询统计速度 select 索引应用
2007/04/11 PHP
Erlang的运算符(比较运算符,数值运算符,移位运算符,逻辑运算符)
2012/07/23 PHP
dedecms集成财付通支付接口
2014/12/28 PHP
PHP SPL标准库之SplFixedArray使用实例
2015/05/12 PHP
PHP加密3DES报错 Call to undefined function: mcrypt_module_open() 如何解决
2016/04/17 PHP
购物车实现的几种方式优缺点对比
2018/05/02 PHP
关于延迟加载JavaScript
2015/05/05 Javascript
jQuery使用ajax跨域获取数据的简单实例
2016/05/18 Javascript
Js遍历键值对形式对象或Map形式的方法
2016/08/08 Javascript
angularJS深拷贝详解
2017/03/23 Javascript
使用 NodeJS+Express 开发服务端的简单介绍
2017/04/07 NodeJs
Vue2.0用户权限控制解决方案的示例
2018/02/10 Javascript
vue 不使用select实现下拉框功能(推荐)
2018/05/17 Javascript
js实现简单分页导航栏效果
2019/06/28 Javascript
JS实现点餐自动选择框(案例分析)
2019/12/10 Javascript
Echarts实现多条折线可拖拽效果
2019/12/19 Javascript
vuex实现购物车的增加减少移除
2020/06/28 Javascript
vue实现用户长时间不操作自动退出登录功能的实现代码
2020/07/23 Javascript
VUE动态生成word的实现
2020/07/26 Javascript
在vue中使用el-tab-pane v-show/v-if无效的解决
2020/08/03 Javascript
在Python中使用mechanize模块模拟浏览器功能
2015/05/05 Python
Python探索之爬取电商售卖信息代码示例
2017/10/27 Python
对pandas将dataframe中某列按照条件赋值的实例讲解
2018/11/29 Python
python实现用户名密码校验
2020/03/18 Python
详解python模块pychartdir安装及导入问题
2020/10/22 Python
CSS3的Flexbox布局的简明入门指南
2016/04/08 HTML / CSS
法拉利英国精品店:Ferraris Boutique UK
2019/07/20 全球购物
万豪国际住宅与别墅集团:Homes & Villas by Marriott International
2020/10/08 全球购物
合作意向协议书范本
2014/03/31 职场文书
个人年终总结怎么写
2015/03/09 职场文书
环保主题班会教案
2015/08/13 职场文书
浅谈JS的原型和原型链
2021/06/04 Javascript
Java输出Hello World完美过程解析
2021/06/13 Java/Android
python可视化大屏库big_screen示例详解
2021/11/23 Python
Python 恐龙跑跑小游戏实现流程
2022/02/15 Python
vue如何实现关闭对话框后刷新列表
2022/04/08 Vue.js