将多孔金属结构图片进行灰度处理,转化成二值图像,只含有黑色和白色像素点,其中白色为孔洞,黑色为金属骨料,进而借助python的PIL库计算白色像素数量占总像素数量的比例,便可将其视为孔隙率。
具体代码如下:
import numpy as np
from PIL import Image
def calculate_porosity(image_path):
# 打开图像并转化为灰度
img = Image.open(image_path).convert('L')
# 转化为数组
img_array = np.array(img)
# 计算色像素的数量
white_pixels = np.sum(img_array == 255)
# 计算总像素的数量
total_pixels = np.size(img_array)
# 计算孔隙率,即白色像素的数量占总像素数量的比例
porosity = white_pixels / total_pixels
return porosity