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


猜你喜欢
- 一、利用Google API生成二维码Google提供了较为完善的二维码生成接口,调用API接口很简单,以下是调用代码:$urlToEnco
- 在使用Context.ResponseWriter中的Set/WriteHeader/Write这三个方法时,使用顺序必须如下所示,否则会出
- 使用fastapi框架开发web项目1、为什么要用fastapi?一直以来博主都是一直使用Django进行开发的,最近公司开始使用fasta
- 一、为什么难 秒杀系统难做的原因:库存只有一份,所有人会在集中的时间读和写这些数据。例如小米手
- 前言本文主要给大家介绍的是关于Python中表达式x += y和x = x+y 区别的相关内容,分享出来供大家参考学习,下面来看看详细的介绍
- 本文详细介绍了asp中如何使用sql语句删除数据库中的记录,初学asp者来看看!1,首先要明确删除哪条记录无非还就是SQL语句了,比如对应到
- 1. 引言Python语言有许多优点,常用于不同的领域,如数据科学、web开发、自动化运维等。开发人员在这些技术中选择Python的一个重要
- 昨天打包下载了一个服务器整站,拿到这个*.mdb的文件后,却不知道怎么用,百度了一下,才知道是一种木马打包的形式文件,不能用WINrar来解
- 一、Flask简介Flask 是一个 Python 实现的 Web 开发微框架。官网:http://flask.pocoo.org/二、De
- 本文首先介绍在python3中print函数的应用,然后对比在pyhton2中的应用。(本文作者所用版本为3.6.0)首先我们通过help(
- 本文实例讲述了Python实现二分查找算法的方法。分享给大家供大家参考。具体实现方法如下:#!/usr/bin/env pythonimpo
- 先上代码:import tensorflow as tfx = tf.ones(shape=[100, 200], dtype=tf.int
- 经常在办公的过程中会遇到各种各样的压缩文件处理,但是呢每个压缩软件支持的格式又是不同的。没有可以一种可以同时多种格式的并且免费的文件解压缩工
- java连接数据库增、删、改、查工具类数据库操作工具类,因为各厂家数据库的分页条件不同,目前支持Mysql、Oracle、Postgresq
- 进行深度学习时,对图像进行预处理的过程是非常重要的,使用pytorch或者TensorFlow时需要对图像进行预处理以及展示来观看处理效果,
- 科讯sql商业版中用到的ajax空间与分页函数,他们的js代码学习是非常不错的//ajax 控件 function Pa
- 前言最近在完成软件体系结构上机实验时,遇到一个有点点小难度的选做题,题目信息如下:利用套接字技术实现应用程序中对数据库的访问。应用程序只是利
- 如果要用某个开源框架,需要安装多个依赖包可以如下操作:如依赖文件形式如下(可以不要版本号):txt文件名为requirements.txt,
- 1. 引言在某些场景下,我们不仅需要进行实时人脸检测追踪,还要进行再加工;这里进行摄像头实时人脸检测,并对于实时检测的人脸进行初步提取;单个
- 学习编写简练、优化的CSS需要大量的实践和一种不自觉的强迫性清洁的渴望。然而让你的CSS保持整洁并不仅仅是你对清洁的疯狂的心理需求,尤其对于