Python实现RLE格式与PNG格式互转
作者:Livingbody 发布时间:2021-07-11 18:23:19
标签: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])
来源:https://juejin.cn/post/7132869631328403493
0
投稿
猜你喜欢
- 从matplotlib工具栏源码探析一(禁用工具栏、默认工具栏和工具栏管理器三种模式的差异)一文可知matplotlib内置实现了多个工具项
- 本方法只做学习研究之用,不得用于商业用途若经济条件允许,请支持并购买正版,链接地址:https://www.jetbrains.com/py
- 背景今天有人问我 “为什么数据库中有人推荐使用 int 类型来保存 IP 地址?”。现在(2020年)来看这个东西已经有点过时了,一方面是磁
- 一、property() 函数讲解了解 @property 装饰器之前,我们首先要了解内置函数的 property()。class prop
- reshape函数:改变数组的维数(注意不是shape大小)>>> e= np.arange(10)>>>
- '*****************************************************************
- 今天在使用Pycharm的时候,由于文件过多,我对目录下的文件做了归类,改动了一些文件的路径,结果后来执行的时候,出现了路径找不到的错误.新
- 一. 元组元组是Python中的一个内置的数据结构,它是一个不可变的序列,所谓的不可变序列就是不可以进行增删改的操作。1.1 元组的创建元组
- close方法可以释放一个连接的资源,但是不是立即释放,如果想立即释放,那么在close之前使用shutdown方法shut_rd() --
- 阅读上一章:打印样式Chapter 12 CSS布局本书到此为止,讨论的主要是页面内部元素,也就是内容,但是大结构怎么办?长久以来,设计者都
- 动手写个小组件(组件入门) 这篇文章主要是为想将自己的ASP水平提高的人写的! 把ASP代码变成组件,开发者不仅是加快了ASP的速度,而且也
- Flask框架是Python开发的一个基于Werkzeug和Jinja 2的web开发微框架,它的优势就是极其简洁, 但又非常灵活,而且容易
- 最近的项目涉及到很多表单的制作,特别是复选框(checkbox)和单选框(radio)。但是在前端开发过程中发现,单(复)选框和它们后面的提
- 很多现代的浏览器在地址栏的右边有个搜索框,默认的安装有 Google 搜索等。如下图所示:其实这是 OpenSearch 的一个应用,只要编
- 众所周知,我们可以通过索引值(或称下标)来查找序列类型(如字符串、列表、元组…)中的单个元素,那么,如果要获取一个索引区间的元素该怎么办呢?
- 这里我不讨论 python 的一些有用的库或者框架,只从语言本身,最小支持的情况下谈论这门语言本身。语言的发展都是越来越接近Lisp,这也是
- 文章首先使用pycharm的 PyQt5 Designer 做一个简单的界面,然后引入所谓的“mvc框架”。一、设计登录界面下面开始第一个话
- WindowsError的错误代码详解0操作成功完成。1功能错误。2系统找不到指定的文件。3系统找不到指定的路径。4系统无法打开文件。5拒绝
- SWFUpload上传组件,最初由Vinterwebb.se开发,组件主体由Flash与JavaScript整合而成,主要致力解决多文件、大
- 最近遇到SQL Server 2005 输入框不能输入中文,在网上查了N久,试验了十几次奏这个法子有用:“把你表中的自动编号列放到最后面”。