影像处理:利用 Numpy 的 histogram 视觉化灰阶影像的强度分布

前言

这边要聊聊,在处理医学影像中的X光片时,要如何将影像的 灰阶值分布 做 视觉化 呈现。
医学影像常见的储存格式是 dicom 档,而X光片通常储存的位元深度是 12 或 16 bits,不过这边会用转换成 png 档案格式、数值型态 uint8 的影像来做示範。

uint8:unsigned interger 8 bits, 0~255

unsigned,是「无符号的意思」,也就是储存的都是正数cf. int8: -255~255,储存範围从负的开始

方法与说明

主要是透过 numpy 中的 histogram [1] 得到数值分布

numpy.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)[source]

再藉由 matplotlib.pyplot 中的 hist [2] 绘製出来

matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)

程式码

import mathimport numpy as npimport matplotlib.pyplot as plt# 以5作为bin的间隔base = 5# 设定上界 (upper_bound) 的目的,是要方便得到bin的分界值upper_bound = math.ceil(image.max()/base + 1) * base# 计算影像中,每个bin累计的数值counts, bin_edges = np.histogram(image, bins=np.arange(0, upper_bound, 5))plt.hist(bin_edges[:-1], bin_edges, weights=counts)plt.xlim(0, 255)

结果

References

[1] Documentation: numpy.histogram
[2] Documentation: matplotlib.pyplot.hist


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章