安装

openslide是处理医学图像经常用到的一个包,因为WSI(whole slide image)是非常大的,在一般情况下是没有办法处理的,所以才要借助openslide进行处理。下面是openslide在ubuntu下的安装方法

pip3 install openslide-python

如果导入时发生报错,那一般是缺少依赖项,在终端运行:

sudo apt install python-openslide

官方地址: https://openslide.org/api/python/

入门

格式问题

首先要说明的一点是openslide的很多API的使用跟python自带的PIL相似,返回的对象是Image对象而不是numpy中array对象,这点需要特别注意。因此在处理上一般都会将其转化为array对象,其默认的通道顺序是RGB。但是还有一点需要注意的是,转化为array对象后是4通道,即在RGB后会再加一个alpha(透明度)通道,其形式为【R,G,B,A】。
关于坐标问题,还是跟python自带的PIL相似,都是(图像的宽,图像的高),跟array中矩阵的顺序(图像的高,图像的宽)是相反的。而基于numpy的OpenCV、skimage在处理图像矩阵是都是先height后width的,即img【height,width】。

常用函数说明

图像读取
import openslide as opsl

slide=opsl.OpenSlide('xxxx.svs')

这里得到的是slide对象,后续对于WSI图像的操作都是基于此。

属性
slide.level_count 

level_count属性是svs图片有多少层金字塔结构。所谓的金字塔结构,就是svs图片已经存储了从上到下每一层采样的图titles,默认情况下0级是原图,每向下一级相当于是对上一级图像的一个下采样,下采样比例一般是4,也可以是2。

slide.level_dimensions

level_dimensions属性是获取指定级下的图像的宽和高,返回的是一个list,每一个元素是一个数组。

slide.level_downsamples

level_downsamples属性返回的是指定级别下的下采样比例,需要注意的是这个数字表示对0级图像的下采样倍数。

提取图像

在opensilde中提取图像有两种方法,分别是get_thumbnail和read_region。get_thumbnail是根据你指定的尺寸,返回原图的缩略图;read_region提取指定层数下指定起始位置和大小的切片截图。在对0层图像(即原图)进行采样和处理中,read_region更常用。需要注意的是,不论是get_thumbnail还是read_region,二者返回的都是python的图像对象,如果需要用别的图像处理工具进行后续的图像处理,比如skimage或opencv,都需要先将其转为numpy格式。

slide_thumbnail = slide.get_thumbnail(slide.level_dimensions[2]) 
# 以2级图像的尺寸作为指定输出的缩略图尺寸返回一个缩略图图像

slide_thumbnail = slide.get_thumbnail((1000,600)) 
# 也可以自己指定一个具体的数值,需要注意的是,第一个参数实际上代表的是宽W,第二个参数代表的是高H
tiles = slide.read_region((location, level, size)
# read_region方法有三组参数,第一组参数是你要提取切片的起始坐标(该坐标是对应曾经下的坐标),
# 第二组参数是你要提取的图像层级
# 第三组参数是切片的尺寸,同样是(宽,高)的形式

这里需要特别注意的location坐标必须是0级图下的坐标,即如果不是取0级图,那么必须将提取切片的起始坐标还原在0级图下的坐标,下面是参数说明。

    def get_thumbnail(self, size):
        """Return a PIL.Image containing an RGB thumbnail of the image.

        size:     the maximum size of the thumbnail."""
    def read_region(self, location, level, size):
        """Return a PIL.Image containing the contents of the region.

        location: (x, y) tuple giving the top left pixel in the level 0
                  reference frame.
        level:    the level number.
        size:     (width, height) tuple giving the region size.

        Unlike in the C interface, the image data returned by this
        function is not premultiplied."""
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐