影像处理:利用 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 math
import numpy as np
import 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


<<:  Ruby基本介绍(三)-P与Puts方法的差异

>>:  [解题纪录] Coin Rows

Day09 | Dart 非同步 - Future

昨天介绍了在Dart中非同步的基本概念,今天就要来讲到如何简单的控制非同步操作。 Future Fu...

第二十九日-MYSQL预存程序 STORED PROCEDURE:来写一个BMI小程序(2)

昨天已经认识分隔符号 DELIMITER和STORED PROCEDURE建立语法, 建立出BMI小...

蓝牙小知识

名称的由来 Bluetooth是斯堪地那维亚语言的Blåtand/Blåtann 借10世纪丹麦和...

Day06:Swift 基础语法—Class

前言 前面学习了 Structure, 今天就来介绍 Class, Structure 与 Clas...

Autofac 如何协助 .NET Core MVC 做 Dependency Injection- 图解概述

Autofac为可以帮忙达成DI的套件,其运作可以参考运作描述,与如何协助ASP.NET MVC达...