OpenCV 机器视觉入门:零件瑕疵检测实验报告(含代码)
实验目的
本实验旨在通过使用 OpenCV 进行图像处理和分析,从而实现零件瑕疵检测。
实验原理
零件瑕疵检测是一项常见的视觉检测任务。在本实验中,我们将使用 OpenCV 进行图像处理和分析,以检测零件的瑕疵。我们将使用以下几个步骤来完成此任务:
- 读取图像并将其转换为灰度图像。
- 对图像进行高斯滤波以去除噪声。
- 对图像进行二值化处理,以便更容易地检测瑕疵。
- 使用形态学操作来填充瑕疵并消除小的噪点。
- 使用轮廓检测来识别瑕疵。
- 将检测到的瑕疵标记在原始图像上。
实验步骤
- 导入必要的库。
import cv2
import numpy as np
- 读取并显示原始图像。
img = cv2.imread('part.jpg')
cv2.imshow('Original Image', img)
cv2.waitKey(0)
- 将图像转换为灰度图像。
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale Image', gray)
cv2.waitKey(0)
- 对图像进行高斯滤波以去除噪声。
blur = cv2.GaussianBlur(gray, (5, 5), 0)
cv2.imshow('Blurred Image', blur)
cv2.waitKey(0)
- 对图像进行二值化处理。
thresh = cv2.threshold(blur, 60, 255, cv2.THRESH_BINARY)[1]
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
- 使用形态学操作来填充瑕疵并消除小的噪点。
kernel = np.ones((5,5), np.uint8)
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
cv2.imshow('Closed Image', closing)
cv2.waitKey(0)
- 使用轮廓检测来识别瑕疵。
contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- 将检测到的瑕疵标记在原始图像上。
for c in contours:
area = cv2.contourArea(c)
if area > 100:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow('Defected Image', img)
cv2.waitKey(0)
完整代码
import cv2
import numpy as np
# Read and display original image
img = cv2.imread('part.jpg')
cv2.imshow('Original Image', img)
cv2.waitKey(0)
# Convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale Image', gray)
cv2.waitKey(0)
# Apply Gaussian blur to remove noise
blur = cv2.GaussianBlur(gray, (5, 5), 0)
cv2.imshow('Blurred Image', blur)
cv2.waitKey(0)
# Apply thresholding to create binary image
thresh = cv2.threshold(blur, 60, 255, cv2.THRESH_BINARY)[1]
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
# Apply morphological closing to fill defects and remove small noise
kernel = np.ones((5,5), np.uint8)
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
cv2.imshow('Closed Image', closing)
cv2.waitKey(0)
# Find contours in the image
contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Mark defects on the original image
for c in contours:
area = cv2.contourArea(c)
if area > 100:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow('Defected Image', img)
cv2.waitKey(0)
# Clean up
cv2.destroyAllWindows()
实验结果
运行上述代码后,我们得到以下结果:

我们可以看到,检测到了几个零件的瑕疵,并将其标记在原始图像上。
结论
本实验使用 OpenCV 实现了图像处理和分析,从而实现了零件瑕疵检测。我们使用了灰度转换、高斯滤波、二值化、形态学操作和轮廓检测等步骤来完成此任务。这个实验可以作为入门级别的 OpenCV 机器视觉项目,帮助我们了解如何使用 OpenCV 进行图像处理和分析。
原文地址: https://www.cveoy.top/t/topic/nY9e 著作权归作者所有。请勿转载和采集!