python-opencv划痕检测-续

python-opencv划痕检测-续

这次划痕检测,是上一次划痕检测的续集。

处理的图像如下:

这次划痕检测,我们经过如下几步:

第一步:读取灰度图像

第二步:进行均值滤波

第三步:进行图像差分

第四步:阈值分割

第五步:轮廓检测

第六步:绘制轮廓,并将过滤面积较小的轮廓,且进行轮廓填充

代码如下:

python 复制代码
import cv2
import copy
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import os


path=r'sta.bmp'

img=cv2.imread(path)

def histogram_equalization(image):
    gray = image
    equalized = cv2.equalizeHist(gray)
    return equalized

# 图像去噪 - 高斯滤波
def gaussian_filtering(image):
    blurred = cv2.GaussianBlur(image, (3, 3), 0)
    return blurred


#img=gaussian_filtering(img)

#img = histogram_equalization(img)
img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)




def cv_show(name,img):
    cv2.imshow(name,img)
    #cv2.waitKey(0),接收0,表示窗口暂停
    cv2.waitKey(0)
    #销毁所有窗口
    cv2.destroyAllWindows()



img_mean_3 = cv2.blur(img_gray, (10, 10))

#图像差分
img_diffence=cv2.subtract(img_mean_3,img_gray)

img_diffence1=img_mean_3-img_gray

plt.subplot(131)
plt.imshow(img_diffence,'gray')
plt.title('img_diffence')


#阈值分割

_,img_binary=cv2.threshold(img_diffence,5,255,cv2.THRESH_BINARY_INV)
plt.subplot(132)
plt.imshow(img_binary,'gray')
plt.title('img_binary')

plt.show()
#cv_show('img

grayimg=img_binary



cout,hi=cv2.findContours(grayimg,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#hierarchy 轮廓层级关系
result=np.zeros(img.shape,np.uint8)

#绘制轮廓边框
for  i in range(len(cout)):
    moms=cv2.moments(cout[i])#计算轮廓的矩
    area=moms['m00']#面积
    if area>50 and area<1000:
            cv2.drawContours(result,cout,i,(0,0,255),thickness=cv2.FILLED,hierarchy=hi,maxLevel=0)


cv_show('result',result)

os.system("pause")

结果如下:

相关推荐
跨境数据猎手42 分钟前
反向海淘实战|独立站搭建+国内电商API对接
开发语言·爬虫·架构
没钥匙的锁11 小时前
05-Java面向对象构造器与封装
java·开发语言
仙人球部落1 小时前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
2401_894915531 小时前
Geo搜索优化排名源码部署搭建全流程详解
android·开发语言·flask·php·精选
蜡笔削薪1 小时前
财联支付异地拓展商户的区域限制是否符合监管规定?
大数据·python
印度神油92 小时前
Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
windows·python·ci/cd
chouchuang2 小时前
day-025-面向对象-上
开发语言·python
sunfdf2 小时前
Next.js 新手从零部署到首跑实战指南
开发语言·javascript·ecmascript
hold?fish:palm3 小时前
从源码到可执行文件:C++程序的编译过程
开发语言·c++
随性而行3603 小时前
微信API接口与AI自动化:开发者的实现思路
运维·服务器·开发语言·人工智能·微信·自动化