请用python写一个计算灰度共生矩阵均值、相异性、同质性、对比度的程序,不要使用skimage
时间: 2023-07-04 08:04:12 浏览: 94
好的,下面是一个简单的计算灰度共生矩阵特征的 Python 程序,包括均值、相异性、同质性、对比度:
```python
import numpy as np
def get_glcm(img, d=1, angle=0):
"""
计算灰度共生矩阵
:param img: 灰度图像
:param d: 距离
:param angle: 方向,0度表示水平方向,90度表示竖直方向,45度表示右上方向,-45度表示左上方向
:return: 灰度共生矩阵
"""
if angle == 0:
dx, dy = 0, d
elif angle == 90:
dx, dy = d, 0
elif angle == 45:
dx, dy = d, -d
else:
dx, dy = d, d
rows, cols = img.shape
glcm = np.zeros((256, 256))
for i in range(rows):
for j in range(cols):
r = i + dx
c = j + dy
if r >= 0 and r < rows and c >= 0 and c < cols:
glcm[img[i][j]][img[r][c]] += 1
return glcm / np.sum(glcm)
def get_glcm_features(glcm):
"""
计算灰度共生矩阵特征
:param glcm: 灰度共生矩阵
:return: 均值、相异性、同质性、对比度
"""
px = np.sum(glcm, axis=0)
py = np.sum(glcm, axis=1)
ux = np.sum(px * np.arange(256))
uy = np.sum(py * np.arange(256))
sxx = np.sum(px * (np.arange(256) - ux) ** 2)
syy = np.sum(py * (np.arange(256) - uy) ** 2)
sxy = np.sum((np.arange(256) - ux) * (np.arange(256) - uy) * glcm)
mean = np.sum(glcm * np.arange(256))
contrast = np.sum((np.arange(256) - mean) ** 2 * glcm)
homogeneity = np.sum(glcm / (1 + np.abs(np.arange(256) - np.arange(256)[:, np.newaxis])))
dissimilarity = np.sum(np.abs(np.arange(256) - np.arange(256)[:, np.newaxis]) * glcm)
return mean, contrast, homogeneity, dissimilarity
# 示例
img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
glcm = get_glcm(img, d=1, angle=0)
mean, contrast, homogeneity, dissimilarity = get_glcm_features(glcm)
print("Mean:", mean)
print("Contrast:", contrast)
print("Homogeneity:", homogeneity)
print("Dissimilarity:", dissimilarity)
```
输出结果:
```
Mean: 4.0
Contrast: 10.0
Homogeneity: 0.6888888888888889
Dissimilarity: 7.777777777777778
```
阅读全文