用python写一段批量读取谋文件夹下所有图片的图像纹理特征的代码,方法用灰度共生矩阵,不用greycomatrix, greycoprops,提取的特征包括对比度(contrast)、均匀性(homogeneity)、能量(energy)、相关性(correlation),并将结果保存到csv文件中
时间: 2023-07-14 15:14:09 浏览: 67
好的,以下是Python代码实现:
```python
import cv2
import os
import numpy as np
import pandas as pd
# 定义保存特征的列表
contrast_list = []
homogeneity_list = []
energy_list = []
correlation_list = []
# 定义灰度共生矩阵函数
def glcm_feature(img_gray):
glcm = np.zeros((256, 256), dtype=np.uint8)
for i in range(img_gray.shape[0]-1):
for j in range(img_gray.shape[1]-1):
glcm[img_gray[i][j]][img_gray[i+1][j]] += 1
glcm = glcm + glcm.T
glcm = glcm.astype(np.float)
glcm = glcm / np.sum(glcm)
contrast = np.sum(np.square(glcm)) - np.square(np.sum(glcm))
homogeneity = np.sum(glcm / (1+np.abs(np.subtract.outer(range(256), range(256)))))
energy = np.sqrt(np.sum(np.square(glcm)))
correlation = np.sum(np.multiply(np.outer(range(256), range(256)), glcm)) - np.multiply(np.mean(range(256)), np.mean(range(256)))
correlation = correlation / (np.sqrt(np.var(range(256))) * np.sqrt(np.var(range(256))))
return contrast, homogeneity, energy, correlation
# 定义遍历文件夹的函数
def traverse_folder(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
img_path = os.path.join(root, file)
img_gray = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
contrast, homogeneity, energy, correlation = glcm_feature(img_gray)
contrast_list.append(contrast)
homogeneity_list.append(homogeneity)
energy_list.append(energy)
correlation_list.append(correlation)
# 调用遍历文件夹函数
folder_path = 'your_folder_path'
traverse_folder(folder_path)
# 将特征保存到csv文件中
df = pd.DataFrame({'Contrast': contrast_list, 'Homogeneity': homogeneity_list, 'Energy': energy_list, 'Correlation': correlation_list})
df.to_csv('glcm_features.csv', index=False)
```
其中,`glcm_feature()`函数用于计算灰度共生矩阵特征,`traverse_folder()`函数用于遍历文件夹并计算每张图片的特征,最后将特征保存到csv文件中。你只需要将`your_folder_path`替换成你自己的图片文件夹路径即可。
阅读全文