代码

  1. import cv2, math
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. ## 定义图像目录
  5. image_directory = 'D:\\Data_documents\\ImageProcess\\images\\'
  6. # 图像读取
  7. imgname = image_directory + 'j.png'
  8. img = cv2.imread(imgname)
  9. # 图像显示在一个新的名字为'image'的窗口中,如果看不到,在任务栏中把窗口恢复后观察图像,在窗口中按任意键关闭窗口
  10. cv2.imshow('image',img)
  11. cv2.waitKey(0)
  12. cv2.destroyAllWindows()

常用操作

1. 腐蚀操作

  1. # 生成结构元
  2. kernel = np.ones((5,5),np.uint8)
  3. erosion = cv2.erode(img,kernel,iterations = 1)
  4. # 显示
  5. cv2.imshow('image',img)
  6. cv2.imshow('image2',erosion)
  7. cv2.waitKey(0)
  8. cv2.destroyAllWindows()

2. 膨胀操作

  1. dilation = cv2.dilate(img,kernel,iterations = 1)
  2. # 显示
  3. cv2.imshow('image',img)
  4. cv2.imshow('image2',dilation)
  5. cv2.waitKey(0)
  6. cv2.destroyAllWindows()

3. 开操作

  1. # 图像读取
  2. imgname = image_directory + 'j2.png'
  3. img = cv2.imread(imgname)
  4. # open operation
  5. opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
  6. # 显示
  7. cv2.imshow('Source image',img)
  8. cv2.imshow('Open',opening)
  9. cv2.waitKey(0)
  10. cv2.destroyAllWindows()

4. 闭操作

  1. # 图像读取
  2. imgname = image_directory + 'j3.png'
  3. img = cv2.imread(imgname)
  4. # open operation
  5. closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
  6. # 显示
  7. cv2.imshow('Source image',img)
  8. cv2.imshow('Close',closing)
  9. cv2.waitKey(0)
  10. cv2.destroyAllWindows()

5. 边缘提取

  1. # OpenCV 中有Morphological Gradient,是图像膨胀与腐蚀之差,可以实现图像的边缘提取
  2. # 图像读取
  3. imgname = image_directory + 'j.png'
  4. img = cv2.imread(imgname)
  5. # open operation
  6. grad = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
  7. # 显示
  8. cv2.imshow('Source image',img)
  9. cv2.imshow('Grad',grad)
  10. cv2.waitKey(0)
  11. cv2.destroyAllWindows()

硬币检测

知识点

6.1 数学形态学概念

6.2 二值图像的形态学处理

  1. 膨胀
  2. 腐蚀
  3. 开运算
  4. 闭运算
  5. 区域填充
  6. 通道分量提取
  7. 区域骨架提取

    6.3 灰度图像的形态学处理

课件

机器视觉-第6章-形态学图像处理.pdf