python-opencv scratch detection-continued

python-opencv scratch detection-continued

This scratch detection is the sequel to the previous scratch detection.

The processed images are as follows:
Insert image description here

For this scratch detection, we went through the following steps:
Step 1: Read the grayscale image
Step 2: Perform mean filtering
Step 3: Perform image difference
Step 4: Threshold segmentation
Step 5: Contour detection
Step 6 : Draw contours, filter contours with smaller areas, and perform contour filling.

code show as below:

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")

The result is as follows:
Insert image description here
Insert image description here

Supongo que te gusta

Origin blog.csdn.net/weixin_43327597/article/details/134561266
Recomendado
Clasificación