我们有某种阴极材料的扫描电子显微镜(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)时就不会了。我是否正确地找到了最暗的像素?
发布于 2019-12-13 06:12:36
如果您将“裂缝”定义为一个暗像素,那么您可以使用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()https://stackoverflow.com/questions/59303163
复制相似问题