Python实现RLE格式与PNG格式互转

 更新时间:2022年08月18日 08:49:34   作者:Livingbody  
在机器视觉领域的深度学习中,很多数据集的标注文件使用RLE的格式。但是神经网络的输入一定是一张图片,为此必须把RLE格式的文件转变为图像格式。本文将利用Python实现RLE格式与PNG格式互转,感兴趣的可以了解一下

介绍

在机器视觉领域的深度学习中,每个数据集都有一份标注好的数据用于训练神经网络。

为了节省空间,很多数据集的标注文件使用RLE的格式。

但是神经网络的输入一定是一张图片,为此必须把RLE格式的文件转变为图像格式。

图像格式主要又分为 .jpg 和 .png 两种格式,其中label数据一定不能使用 .jpg,因为它因为压缩算算法的原因,会造成图像失真,图像各个像素的值可能会发生变化。分割任务的数据集的 label 图像中每一个像素都代表了该像素点所属的类别,所以这样的失真是无法接受的。为此只能使用 .png 格式作为label,pascol voc 和 coco 数据集正是这样做的。

1.PNG2RLE

PNG格式转RLE格式

#!---- coding: utf- ---- import numpy as np

def rle_encode(binary_mask):
    '''
    binary_mask: numpy array, 1 - mask, 0 - background
    Returns run length as string formated
    '''
    pixels = binary_mask.flatten()
    pixels = np.concatenate([[0], pixels, [0]])
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
    runs[1::2] -= runs[::2]
    return ' '.join(str(x) for x in runs)

2.RLE2PNG

RLE格式转PNG格式

#!--*-- coding: utf- --*--
import numpy as np

def rle_decode(mask_rle, shape):
    '''
    mask_rle: run-length as string formated (start length)
    shape: (height,width) of array to return
    Returns numpy array, 1 - mask, 0 - background
    '''
    s = mask_rle.split()
    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
    starts -= 1
    ends = starts + lengths
    binary_mask = np.zeros(shape[0] * shape[1], dtype=np.uint8)
    for lo, hi in zip(starts, ends):
        binary_mask[lo:hi] = 1
    return binary_mask.reshape(shape)

3.示例

'''
RLE: Run-Length Encode
'''
from PIL import Image
import numpy as np 

def __main__():
    maskfile = '/path/to/test.png'
    mask = np.array(Image.open(maskfile))
    binary_mask = mask.copy()
    binary_mask[binary_mask <= 127] = 0
    binary_mask[binary_mask > 127] = 1

    # encode
    rle_mask = rle_encode(binary_mask)
    
    # decode
    binary_mask_decode = self.rle_decode(rle_mask, binary_mask.shape[:2])

4.完整代码如下

'''
RLE: Run-Length Encode
'''
#!--*-- coding: utf- --*--
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt


# M1:
class general_rle(object):
    '''
    ref.: https://www.kaggle.com/stainsby/fast-tested-rle
    '''
    def __init__(self):
        pass


    def rle_encode(self, binary_mask):
        pixels = binary_mask.flatten()
        # We avoid issues with '1' at the start or end (at the corners of
        # the original image) by setting those pixels to '0' explicitly.
        # We do not expect these to be non-zero for an accurate mask,
        # so this should not harm the score.
        pixels[0] = 0
        pixels[-1] = 0
        runs = np.where(pixels[1:] != pixels[:-1])[0] + 2
        runs[1::2] = runs[1::2] - runs[:-1:2]
        return runs


    def rle_to_string(self, runs):
        return ' '.join(str(x) for x in runs)


    def check(self):
        test_mask = np.asarray([[0, 0, 0, 0],
                                [0, 0, 1, 1],
                                [0, 0, 1, 1],
                                [0, 0, 0, 0]])
        assert rle_to_string(rle_encode(test_mask)) == '7 2 11 2'


# M2:
class binary_mask_rle(object):
    '''
    ref.: https://www.kaggle.com/paulorzp/run-length-encode-and-decode
    '''
    def __init__(self):
        pass

    def rle_encode(self, binary_mask):
        '''
        binary_mask: numpy array, 1 - mask, 0 - background
        Returns run length as string formated
        '''
        pixels = binary_mask.flatten()
        pixels = np.concatenate([[0], pixels, [0]])
        runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
        runs[1::2] -= runs[::2]
        return ' '.join(str(x) for x in runs)


    def rle_decode(self, mask_rle, shape):
        '''
        mask_rle: run-length as string formated (start length)
        shape: (height,width) of array to return
        Returns numpy array, 1 - mask, 0 - background
        '''
        s = mask_rle.split()
        starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
        starts -= 1
        ends = starts + lengths
        binary_mask = np.zeros(shape[0] * shape[1], dtype=np.uint8)
        for lo, hi in zip(starts, ends):
            binary_mask[lo:hi] = 1
        return binary_mask.reshape(shape)

    def check(self):
        maskfile = '/path/to/test.png'
        mask = np.array(Image.open(maskfile))
        binary_mask = mask.copy()
        binary_mask[binary_mask <= 127] = 0
        binary_mask[binary_mask > 127] = 1

        # encode
        rle_mask = self.rle_encode(binary_mask)

        # decode
        binary_mask2 = self.rle_decode(rle_mask, binary_mask.shape[:2])

到此这篇关于Python实现RLE格式与PNG格式互转的文章就介绍到这了,更多相关Python RLE转PNG内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python实现自动发送测试报告邮件的示例代码

    Python实现自动发送测试报告邮件的示例代码

    SMTP也就是简单邮件传输协议,是一种提供可靠且有效电子邮件传输的协议,python的smtplib模块就提供了一种很方便的途径发送电子邮件,它对smtp协议进行了简单的封装,下面就来和大家简单聊聊吧
    2023-07-07
  • Python Selenium截图功能实现代码

    Python Selenium截图功能实现代码

    这篇文章主要介绍了Python Selenium截图功能实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Python全栈之强制转换

    Python全栈之强制转换

    这篇文章主要为大家介绍了Python强制转换,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-12-12
  • python创建堆的方法实例讲解

    python创建堆的方法实例讲解

    在本篇文章里小编给大家整理的是一篇关于python创建堆的方法实例讲解内容,有兴趣的朋友们可以学习下。
    2021-03-03
  • Tkinter组件Checkbutton的具体使用

    Tkinter组件Checkbutton的具体使用

    Checkbutton组件用于实现确定是否选择的按钮,本文主要介绍了Tkinter组件Checkbutton的具体使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • python pyecharts 实现一个文件绘制多张图

    python pyecharts 实现一个文件绘制多张图

    这篇文章主要介绍了python pyecharts 实现一个文件绘制多张图,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python爬虫基础之requestes模块

    Python爬虫基础之requestes模块

    这篇文章主要介绍了Python爬虫基础之requestes模块,文中有非常详细的代码示例,对正在学习python爬虫的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • 利用Python脚本实现传递参数的三种方式分享

    利用Python脚本实现传递参数的三种方式分享

    使用python脚本传递参数在实际工作过程中还是比较常用。这篇文章为大家总结了三个常用的方式,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-12-12
  • 对Python 字典元素进行删除的方法

    对Python 字典元素进行删除的方法

    这篇文章主要介绍了对Python 字典元素进行删除的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • python 运算符 供重载参考

    python 运算符 供重载参考

    二元运算符及其对应的特殊方法
    2009-06-06

最新评论