** 我想要做的是使用 Python 3.0x 快速计算 GLCM 特征,并且应该在每个图像上绘制整个图像组的特征平均值以及图像的单个特征值。没有平均值的示例图像是这样的。并且特征值包括熵、对比度、角二阶矩等。任何加速这个过程的想法都值得赞赏。**
gray_level = 64
def maxGrayLevel(img):
max_gray_level = 0
(height, width) = img.shape
print(height, width)
for y in range(height):
for x in range(width):
if img[y][x] > max_gray_level:
max_gray_level = img[y][x]
return max_gray_level + 1
def getGlcm(input, d_x, d_y):
srcdata = input.copy()
ret = [[0.0 for i in range(gray_level)] for j in range(gray_level)]
(height, width) = input.shape
max_gray_level = maxGrayLevel(input)
# 若灰度级数大于gray_level,则将图像的灰度级缩小至gray_level,减小灰度共生矩阵的大小
if max_gray_level > gray_level:
for j in range(height):
for i in range(width):
srcdata[j][i] = srcdata[j][i] * gray_level / max_gray_level
for j in range(height - d_y):
for i in range(width - d_x):
rows = srcdata[j][i]
cols = srcdata[j + d_y][i + d_x]
ret[rows][cols] += 1.0
for i in range(gray_level):
for j in range(gray_level):
ret[i][j] /= float(height * width)
return ret
def feature_computer(p):
'''
:param p: 单张灰度图片矩阵
:return: 四个 GLCM 特征值
'''
Con = 0.0
Ent = 0.0
Asm = 0.0
Idm = 0.0
for i in range(gray_level):
for j in range(gray_level):
Con += (i - j) * (i - j) * p[i][j]
Asm += p[i][j] * p[i][j]
Idm += p[i][j] / (1 + (i - j) * (i - j))
if p[i][j] > 0.0:
Ent += p[i][j] * math.log(p[i][j])
return Asm, Con, -Ent, Idm
def Put_text(im_path):
# for im_path in files:
im_name = im_path.split('\\')[-1]
suffix_path = im_path.split('\\')[-2]
new_path_head = r'I:\DATA\Texture-based-data\annot_texture'
new_path = os.path.join(new_path_head, suffix_path)
new_root_im_name = os.path.join(new_path, im_name)
if not os.path.exists(new_path):
os.makedirs(new_path)
if not os.path.exists(new_root_im_name):
im = cv2.imread(im_path)
try:
img_shape = im.shape
except:
print('imread error')
return
img = cv2.resize(im, (int(img_shape[1] / 2), int(img_shape[0] / 2)), interpolation=cv2.INTER_CUBIC)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
glcm_0 = getGlcm(img_gray, 1, 0)
asm, con, ent, idm = feature_computer(glcm_0)
imgzi = New_put_text('asm'+str(asm)+'\n'+'con'+str(con)+'\n'+'ent'+str(ent)+'\n'+'idm'+str(idm), img)
cv2.imwrite(new_root_im_name, img)
print(new_root_im_name, '\n', getImageVar(im), asm, con, ent, idm)
if __name__ == '__main__':
subfiles = [f for f in glob.glob(os.path.join(sub_files, r'*bmp'))]
p = Pool(4)
p.map(Put_text, subfiles)