python - 查找 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)
。我是否正确找到了最暗的像素?
解决方案
如果将“裂缝”定义为暗像素,则可以使用它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()
推荐阅读
- api - 沃尔玛 API - 公钥上传失败
- ios - 使用带有多个参数的 @objc 委托方法
- javascript - 我必须在 Next.js 项目中使用 express 吗?
- javascript - 如何使用 fs.writefile 创建 HTML 文件
- javascript - 下面是我一直在处理的索引页面的 html。我想编辑和删除数据表中的按钮但不工作
- python - 需要帮助找出一个循环来缩短某些代码的长度
- c - 为什么字节地址在下面的示例中只存储 2 位数字?
- windows - 用于递归遍历并查找特定文件类型的 bat 文件
- ios - 为什么尽管安装了相同的代码,但不同的设备从 HD 返回相同集合的不同顺序
- c++ - 为什么我可以在 C++ 的一个范围内重新声明变量?