首页 > 解决方案 > 查找 SEM 图像中“裂纹”的百分比

问题描述

我们有某种阴极材料的扫描电子显微镜 (SEM) 图像,我的目标是找出图像中有多少百分比被裂缝占据。关于如何做到这一点的任何建议?目前,我只是尝试找出图像中“最暗”像素的数量,并取图像中像素总数的百分比。在此处输入图像描述

到目前为止,这是我的代码:

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "path to input image")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY)[1]
#imageCanny = cv2.Canny(blurred, 100, 200, 3)


#total number of pixels in the image = 1280x960 = 1228800
count = cv2.countNonZero(thresh)
img, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image, contours, -1, (0,255,255), 2)
print(count)

如果我这样做了,countNonZero(image)我会得到错误(-215) cn == 1 in function countNonZero,但当我这样做时不会countNonZero(thresh)。我是否正确找到了最暗的像素?

标签: pythonopencvimage-processingphysicspixel

解决方案


如果将“裂缝”定义为暗像素,则可以使用它np.where()来隔离低于某个阈值的裂缝。基本上任何低于此阈值的像素都将被定义为裂纹。这将为您提供一个灰度图像,您可以使用它cv2.countNonZero()来确定裂纹百分比。使用阈值30(可以在 的范围内调整[0..255])结果如下:

在此处输入图像描述

Crack percentage: 16.74%

代码

import cv2
import numpy as np

# Load image as grayscale, change all pixels less than some threshold to black
image = cv2.imread('1.jpg', 0)
w,h = image.shape
image[np.where(image <= 30)] = 0

# Count non-crack pixels
pixels = cv2.countNonZero(image)

# Calculate crack percentage
percentage = 100 - (pixels / (w * h)) * 100
print('Crack percentage: {:.2f}%'.format(percentage))

cv2.imshow('image', image)
cv2.waitKey()

推荐阅读