代码
import cv2, math
import numpy as np
import matplotlib.pyplot as plt
## 定义图像目录
image_directory = 'D:\\Data_documents\\ImageProcess\\images\\'
# 图像读取
imgname = image_directory + 'j.png'
img = cv2.imread(imgname)
# 图像显示在一个新的名字为'image'的窗口中,如果看不到,在任务栏中把窗口恢复后观察图像,在窗口中按任意键关闭窗口
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
常用操作
1. 腐蚀操作
# 生成结构元
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(img,kernel,iterations = 1)
# 显示
cv2.imshow('image',img)
cv2.imshow('image2',erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. 膨胀操作
dilation = cv2.dilate(img,kernel,iterations = 1)
# 显示
cv2.imshow('image',img)
cv2.imshow('image2',dilation)
cv2.waitKey(0)
cv2.destroyAllWindows()
3. 开操作
# 图像读取
imgname = image_directory + 'j2.png'
img = cv2.imread(imgname)
# open operation
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
# 显示
cv2.imshow('Source image',img)
cv2.imshow('Open',opening)
cv2.waitKey(0)
cv2.destroyAllWindows()
4. 闭操作
# 图像读取
imgname = image_directory + 'j3.png'
img = cv2.imread(imgname)
# open operation
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
# 显示
cv2.imshow('Source image',img)
cv2.imshow('Close',closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
5. 边缘提取
# OpenCV 中有Morphological Gradient,是图像膨胀与腐蚀之差,可以实现图像的边缘提取
# 图像读取
imgname = image_directory + 'j.png'
img = cv2.imread(imgname)
# open operation
grad = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
# 显示
cv2.imshow('Source image',img)
cv2.imshow('Grad',grad)
cv2.waitKey(0)
cv2.destroyAllWindows()
硬币检测
知识点
6.1 数学形态学概念
6.2 二值图像的形态学处理
- 膨胀
- 腐蚀
- 开运算
- 闭运算
- 区域填充
- 通道分量提取
- 区域骨架提取
6.3 灰度图像的形态学处理
课件
机器视觉-第6章-形态学图像处理.pdf