通过“ def compress(S)”进行图像压缩。使用游程编码的功能 [英] Image compression by "def compress(S)" function using run-length encoding
问题描述
我需要编写一个名为 compress(S)
的函数,该函数需要一个长度小于以下内容的二进制字符串 S
等于64作为输入,并返回另一个二进制字符串作为输出。输出的二进制字符串应为输入字符串的游程长度编码。
I need to write a function called compress(S)
that takes a binary string S
of length less than or equal to 64 as input and returns another binary string as output. The output binary string should be a run-length encoding of the input string.
游程长度编码按序列(称为游程序列)表示图像)的8位字节:
Run-length coding represents an image by a sequence (called a "run-length sequence") of 8-bit bytes:
每个字节的第一位代表将在图像中显示的下一位,即0或1。
最后七个位包含在图像的当前位置连续出现的那些位的二进制数。
The first bit of each byte represents the bit that will appear next in the image, either 0 or 1. The final seven bits contain the number in binary of those bits that appear consecutively at the current location in the image.
>>>compress( 64*'0' )
'01000000'
>>> compress( '11111' )
'10000101'
>>> Stripes = '0'*16 + '1'*16 + '0'*16 + '1'*16
>>> compress(Stripes)
'00010000100100000001000010010000'
推荐答案
首次运行长度编码,将其定义为-
First Run Length Encoding, define it as-
def rle(input_string):
""" takes input as string and checks repeating bit
return repeating bit with their counts.
"""
count = 1
prev = ''
lst = []
for character in input_string:
if character != prev:
if prev:
entry = (prev,count)
lst.append(entry)
#print lst
count = 1
prev = character
else:
count += 1
else:
entry = (character,count)
lst.append(entry)
return lst
生成元组列表。
输入:print rle('1111010')
Input: print rle('1111010')
输出:[('1',4), ('0',1),('1',1),('0',1)]
Output: [('1', 4), ('0', 1), ('1', 1), ('0', 1)]
----------------------------------
现在使用此列表制作具有重复计数的二进制转换的字典,并将其格式化为7位长。最后添加字典的相应键和值,以便总位数保持8位。
Now use this list to make dictionary with binary conversion of repeating counts and format it to 7 bits long. And finally add the respective key and values of the dict so that total digit remain 8 bits.
def new_dict(S):
""" input of rle(S) i.e., tuples of bit and repeating counts
output dict as bit as key and value as counts with binary conversion.
"""
dict=rle(S)
new_dict = []
temp = []
for k,v in dict:
temp = k + "%07d" % int(bin(v)[2:])
new_dict.append(temp)
return new_dict
输入:打印new_dict('1111010')
input: print new_dict('1111010')
输出:['10000100','00000001','10000001','00000001']
output: ['10000100', '00000001', '10000001', '00000001']
现在使用compress(S)函数压缩此二进制字符串。
Now compress this binary string with the compress(S) function.
def compress(S):
""" takes a binary string S of length less than or equal to 64 as input and returns another binary string as output.
"""
l = new_dict(S)
return''.join(str(elem) for elem in l)
打印压缩('1111010')
打印压缩(64 *'0')
print compress('1111010')
print compress( 64*'0' )
print compress('11111')
print compress( '11111' )
条纹='0'* 16 +'1'* 16 +'0'* 16 +'1'* 16
Stripes = '0'*16 + '1'*16 + '0'*16 + '1'*16
打印压缩(条纹)
这篇关于通过“ def compress(S)”进行图像压缩。使用游程编码的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!