1.共现矩阵
灰度共生矩阵
- 先将图像转换成灰度图片
- 然后再用
graycomatirx
函数进行共生矩阵计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import cv2 import numpy as np np.set_printoptions(suppress=True)
def glcm(arr, d_x, d_y, gray_level=16): '''计算并返回归一化后的灰度共生矩阵''' max_gray = arr.max() height, width = arr.shape arr = arr.astype(np.float64) arr = arr * (gray_level - 1) // max_gray ret = np.zeros([gray_level, gray_level]) for j in range(height - abs(d_y)): for i in range(width - abs(d_x)): rows = arr[j][i].astype(int) cols = arr[j + d_y][i + d_x].astype(int) ret[rows][cols] += 1 if d_x >= d_y: ret = ret / float(height * (width - 1)) else: ret = ret / float((height - 1) * (width - 1)) return ret
if __name__=='__main__': '''归一化时分母值根据角度theta变化,0度或90度时为height * (width - 1), 45度或135度时为(height - 1) * (width - 1)''' fp = r'/home/jovyan/work/000.png' img = cv2.imread(fp) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) glcm_1 = glcm(img_gray, 0, 1) print(glcm_1)
np.save('/home/jovyan/work/glcm_1.npy', glcm_1)
|
我们将npy.文件格式转换为csv,再转化为Excel文件