纹理特征提取:
'''
#纹理分析:主要是提取和分析图像灰度空间分布模式
#方法:统计、结构两种
#常用的数字纹理特征:图像局部区域的自相关函数、灰度共生矩阵、灰度游程以及灰度分布的各种统计量
#该方法中采用的是灰度共生矩阵
#过程:通过计算灰度图像得到它的共生矩阵,然后透过计算这个共生矩阵得到矩阵的部分特征值,来分别代表图像的某些纹理特征
可反映图像灰度关于方向、相邻间隔、变化幅度的综合信息
'''
import os
import numpy as np
from cv2 import cv2
import json
from tqdm import tqdm
from skimage.feature import greycomatrix, greycoprops
PATH = "../leaf/"
TRAIN = "train_831/"
TEST = "test_351/"
TYPE = ["B2F", "B3F", "C2F", "C3F", "C4F"]
def draw_texture(img):
img = np.array(img)
# 首先框出烟叶
img = np.where(img > 20, img, 0)
# 按行,列加和
weight = np.sum(img, axis=0)
height = np.sum(img, axis=1)
h_zero = []
w_zero = []
for index, h in enumerate(height):
if h == 0:
h_zero.append(index)
for index, w in enumerate(weight):
if w == 0:
w_zero.append(index)
img = np.delete(img, h_zero, axis=0)
img = np.delete(img, w_zero, axis=1)
# 提取烟叶的长宽
shape = img.shape
# 提取烟叶纹理
glcm = greycomatrix(img, distances=[1], angles=[0, np.pi / 4, np.pi / 2, np.pi * 3 / 4], levels=256,
symmetric=False, normed=False)
texture = [shape[0], shape[1],
greycoprops(glcm, 'contrast')[0, 0],
greycoprops(glcm, 'dissimilarity')[0, 0],
greycoprops(glcm, 'homogeneity')[0, 0],
greycoprops(glcm, 'correlation')[0, 0],
greycoprops(glcm, 'energy')[0, 0],
greycoprops(glcm, 'ASM')[0, 0]]
return texture
def process(path, type):
fileList = os.listdir(path)
result = []
for filename in tqdm(fileList):
img = cv2.imread(path + '/' + filename, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (256, 512))
texture = draw_texture(img)
texture.append(type)
result.append(texture)
return result
if __name__ == '__main__':
result = []
for index, type in enumerate(TYPE):
path = PATH + TRAIN + type
result = result + process(path, index)
mm = {"train_data": result}
with open('./dataset_train1.json', 'w+') as json_file:
json.dump(mm, json_file)
# result = []
# for index, type in enumerate(TYPE):
# path = PATH + TEST + type
# result = result + process(path, index)
# mm = {"test_data": result}
# with open('./dataset_test.json', 'w+') as json_file:
# json.dump(mm, json_file)