用图像差分法进行图像缺陷检测,用给出的完整玻璃图像与文件夹中的待测图片集西,将缺陷图像输出到output文件夹的python 代码
时间: 2023-12-03 10:47:46 浏览: 48
以下是使用Python实现图像差分法进行图像缺陷检测的代码:
```
import cv2
import os
# 完整玻璃图像的路径
full_image_path = "full_image.jpg"
# 待测图片集所在的文件夹路径
test_images_path = "test_images/"
# 缺陷图像输出的文件夹路径
output_path = "output/"
# 读取完整玻璃图像
full_image = cv2.imread(full_image_path)
# 遍历待测图片集
for filename in os.listdir(test_images_path):
if filename.endswith(".jpg"):
# 读取待测图片
test_image = cv2.imread(os.path.join(test_images_path, filename))
# 计算差分图像
diff_image = cv2.absdiff(full_image, test_image)
# 将差分图像转换为灰度图像
gray_diff_image = cv2.cvtColor(diff_image, cv2.COLOR_BGR2GRAY)
# 进行二值化处理,将像素值大于阈值的设为255,其余设为0
_, binary_image = cv2.threshold(gray_diff_image, 30, 255, cv2.THRESH_BINARY)
# 判断二值化后的图像中是否存在白色像素点,如果存在则说明存在缺陷
if cv2.countNonZero(binary_image) > 0:
# 将缺陷图像输出到output文件夹中
cv2.imwrite(os.path.join(output_path, filename), binary_image)
```
注意事项:
- 图像路径需要根据实际情况进行修改。
- 代码中使用的阈值为30,需要根据实际情况进行调整。
- 代码中假设待测图片集中只包含jpg格式的图片,如果包含其他格式的图片需要进行相应的修改。