OpenCV机器视觉入门实验:图像处理、特征提取与匹配
一、实验目的
本实验旨在通过 OpenCV 实现机器视觉的基本功能,包括图像的读取、显示、转换、滤波、二值化、轮廓检测、特征提取和匹配等。
二、实验环境
- 操作系统:Ubuntu 18.04 LTS
- 编程语言:Python 3.6.9
- 开发环境:PyCharm 2020.1
- 库:OpenCV 4.4.0
三、实验过程
1. 图像的读取和显示
使用 cv2.imread() 函数读取一张图像,使用 cv2.imshow() 函数显示图像。
import cv2
img = cv2.imread('lena.jpg') # 读取图像
cv2.imshow('image', img) # 显示图像
cv2.waitKey(0) # 等待按键响应
cv2.destroyAllWindows() # 关闭所有窗口
结果:

2. 图像的转换
使用 cv2.cvtColor() 函数将图像从 BGR 格式转换为灰度格式。使用 cv2.cvtColor() 函数将图像从灰度格式转换为 BGR 格式。
import cv2
img = cv2.imread('lena.jpg') # 读取图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
cv2.imshow('gray', gray) # 显示灰度图像
bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) # 转换为 BGR 图像
cv2.imshow('bgr', bgr) # 显示 BGR 图像
cv2.waitKey(0) # 等待按键响应
cv2.destroyAllWindows() # 关闭所有窗口
结果:


3. 图像的滤波
使用 cv2.blur() 函数进行均值滤波。使用 cv2.GaussianBlur() 函数进行高斯滤波。
import cv2
img = cv2.imread('lena.jpg') # 读取图像
blur = cv2.blur(img, (5, 5)) # 均值滤波
cv2.imshow('blur', blur) # 显示均值滤波图像
gaussian = cv2.GaussianBlur(img, (5, 5), 0) # 高斯滤波
cv2.imshow('gaussian', gaussian) # 显示高斯滤波图像
cv2.waitKey(0) # 等待按键响应
cv2.destroyAllWindows() # 关闭所有窗口
结果:


4. 图像的二值化
使用 cv2.threshold() 函数进行阈值分割。
import cv2
img = cv2.imread('lena.jpg') # 读取图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 二值化
cv2.imshow('binary', binary) # 显示二值化图像
cv2.waitKey(0) # 等待按键响应
cv2.destroyAllWindows() # 关闭所有窗口
结果:

5. 轮廓检测
使用 cv2.findContours() 函数进行轮廓检测。使用 cv2.drawContours() 函数将轮廓绘制在图像上。
import cv2
img = cv2.imread('lena.jpg') # 读取图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 二值化
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 轮廓检测
cv2.drawContours(img, contours, -1, (0, 0, 255), 2) # 绘制轮廓
cv2.imshow('contours', img) # 显示轮廓图像
cv2.waitKey(0) # 等待按键响应
cv2.destroyAllWindows() # 关闭所有窗口
结果:

6. 特征提取和匹配
使用 cv2.SIFT() 函数提取图像的 SIFT 特征。使用 cv2.BFMatcher() 函数进行特征匹配。
import cv2
img1 = cv2.imread('lena.jpg') # 读取图像 1
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
sift = cv2.SIFT_create() # 创建 SIFT 特征提取器
kp1, des1 = sift.detectAndCompute(gray1, None) # 提取图像 1 的 SIFT 特征
img2 = cv2.imread('lena_rotated.jpg') # 读取图像 2
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
kp2, des2 = sift.detectAndCompute(gray2, None) # 提取图像 2 的 SIFT 特征
bf = cv2.BFMatcher() # 创建 BFMatcher 匹配器
matches = bf.match(des1, des2) # 特征匹配
matches = sorted(matches, key=lambda x: x.distance) # 根据距离排序
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=2) # 绘制匹配结果
cv2.imshow('matches', img3) # 显示匹配结果
cv2.waitKey(0) # 等待按键响应
cv2.destroyAllWindows() # 关闭所有窗口
结果:

四、实验总结
本实验通过使用 OpenCV 库实现了机器视觉的基本功能,包括图像的读取、显示、转换、滤波、二值化、轮廓检测、特征提取和匹配等。实验结果表明,OpenCV 是一款强大的机器视觉库,能够快速、高效地实现各种机器视觉任务。
原文地址: https://www.cveoy.top/t/topic/nYTy 著作权归作者所有。请勿转载和采集!