用python写一段批量读取谋文件夹下所有图片的图像纹理特征的代码,方法用灰度共生矩阵,不用greycomatrix, greycoprops,提取的特征包括对比度(contrast)、均匀性(homogeneity)、能量(energy)、相关性(correlation),并将结果保存到csv文件中
时间: 2023-07-14 08:14:07 浏览: 101
好的,我来给您提供一下代码,需要先安装一下`numpy`和`opencv-python`库:
```python
import os
import cv2
import numpy as np
import csv
# 定义灰度共生矩阵计算函数
def glcm_feature(img_gray, d_x, d_y):
max_gray = img_gray.max() + 1
glcm = np.zeros((max_gray, max_gray), dtype=np.uint32)
for i in range(img_gray.shape[0]-d_x):
for j in range(img_gray.shape[1]-d_y):
glcm[img_gray[i][j]][img_gray[i+d_x][j+d_y]] += 1
# 归一化
glcm /= np.sum(glcm)
# 计算特征
contrast = 0
homogeneity = 0
energy = 0
correlation = 0
for i in range(max_gray):
for j in range(max_gray):
contrast += ((i-j)**2) * glcm[i][j]
homogeneity += glcm[i][j] / (1 + (i-j)**2)
energy += glcm[i][j]**2
correlation += (i*j*(glcm[i][j]-np.sum(glcm[i,:])*np.sum(glcm[:,j]))) / (np.sqrt(np.var(glcm[i,:]))*np.sqrt(np.var(glcm[:,j])))
return contrast, homogeneity, energy, correlation
# 定义目标文件夹路径
folder_path = r'C:\Users\example\images'
# 获取目标文件夹下所有图片文件名
img_names = [f for f in os.listdir(folder_path) if f.endswith('.jpg') or f.endswith('.png')]
# 定义特征列表
features = []
# 遍历所有图片,计算特征并保存到列表中
for img_name in img_names:
# 读取图片并转换为灰度图像
img = cv2.imread(os.path.join(folder_path, img_name))
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算特征
contrast, homogeneity, energy, correlation = glcm_feature(img_gray, 1, 0)
# 将特征保存到列表中
features.append([img_name, contrast, homogeneity, energy, correlation])
# 将特征列表保存到csv文件中
with open('features.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['image name', 'contrast', 'homogeneity', 'energy', 'correlation'])
writer.writerows(features)
```
这段代码会遍历指定文件夹下的所有`.jpg`和`.png`图片,计算每张图片的特征,并将结果保存到`features.csv`文件中。其中`glcm_feature()`函数是用于计算灰度共生矩阵特征的函数。
阅读全文