图像的编码解码、压缩

图像的编码

# 树节点类构建
class TreeNode(object):
    def __init__(self, data):
        self.val = data[0]
        self.priority = data[1]
        self.leftChild = None
        self.rightChild = None
        self.code = ""
# 创建树节点队列函数
def creatnodeQ(codes):
    q = []
    for code in codes:
        q.append(TreeNode(code))
    return q
# 为队列添加节点元素,并保证优先度从大到小排列
def addQ(queue, nodeNew):
    if len(queue) == 0:
        return [nodeNew]
    for i in range(len(queue)):
        if queue[i].priority >= nodeNew.priority:
            return queue[:i] + [nodeNew] + queue[i:]
    return queue + [nodeNew]
# 节点队列类定义
class nodeQeuen(object):

    def __init__(self, code):
        self.que = creatnodeQ(code)
        self.size = len(self.que)

    def addNode(self,node):
        self.que = addQ(self.que, node)
        self.size += 1

    def popNode(self):
        self.size -= 1
        return self.que.pop(0)
# 各个字符在字符串中出现的次数,即计算优先度
def freChar(string):
    d ={}
    for c in string:
        if not c in d:
            d[c] = 1
        else:
            d[c] += 1
    return sorted(d.items(),key=lambda x:x[1])
# 创建哈夫曼树
def creatHuffmanTree(nodeQ):
    while nodeQ.size != 1:
        node1 = nodeQ.popNode()
        node2 = nodeQ.popNode()
        r = TreeNode([None, node1.priority+node2.priority])
        r.leftChild = node1
        r.rightChild = node2
        nodeQ.addNode(r)
    return nodeQ.popNode()

codeDic1 = {}
codeDic2 = {}
# 由哈夫曼树得到哈夫曼编码表
def HuffmanCodeDic(head, x):
    global codeDic, codeList
    if head:
        HuffmanCodeDic(head.leftChild, x+'0')
        head.code += x
        if head.val:
            codeDic2[head.code] = head.val
            codeDic1[head.val] = head.code
        HuffmanCodeDic(head.rightChild, x+'1')
# 字符串编码
def TransEncode(string):
    global codeDic1
    transcode = ""
    for c in string:
        transcode += codeDic1[c]
    return transcode
# 字符串解码
def TransDecode(StringCode):
    global codeDic2
    code = ""
    ans = ""
    for ch in StringCode:
        code += ch
        if code in codeDic2:
            ans += codeDic2[code]
            code = ""
    return ans
# 举例
string = "AAGGDCCCDDDGFBBBFFGGDDDDGGGEFFDDCCCCDDFGAAA"
t = nodeQeuen(freChar(string))
tree = creatHuffmanTree(t)
HuffmanCodeDic(tree, '')
print('codeDic1:\n',codeDic1)
print('ccodeDic2:\n',codeDic2)
a = TransEncode(string)
print('TransEncode:\n',a)
aa = TransDecode(a)
print('TransDecode:\n',aa)
print(string == aa)


图像解码

class ArtimeticCoding(object):
    def __init__(self, symbol, P, _range=1., _low=0.):
        self.__symbol = [str(s) for s in symbol]
        self.__P = P
        self.__range = _range
        self.__low = _low
        if sum(self.__P) > 1.:
            raise Exception('InitialError', 'Probability sum bigger than 1.')
        if len(self.__P) != len(self.__symbol):
            raise Exception('InitialError', 'Probability and symbol not match.')
        self.__map = self.__symbol_map()

    def __symbol_map(self):
        __map = {}
        __mark = 0.
        for sidx in range(len(self.__symbol)):
            __map[self.__symbol[sidx]] = {'from': __mark, 'to': __mark + self.__P[sidx]}
            __mark += self.__P[sidx]
        return __map

    def encode(self, seq=''):
        return self.__encode(seq, self.__range, self.__low)

    def __encode(self, s, __range, __low):
        if s[0] not in self.__map:
            raise Exception('SymbolError', 'unknown symbol occurred.')
        __low2 = __low + __range * self.__map[s[0]]['from']
        __high2 = __low + __range * self.__map[s[0]]['to']
        print(s[0], __high2, __low2)
        if len(s) == 1:
            return __low2
        else:
            return self.__encode(s[1:], __high2 - __low2, __low2)

if __name__ == '__main__':
    ac = ArtimeticCoding([0, 1, 2], [0.25, 0.5, 0.25])
    print(ac.encode('10210'))

图像的压缩

求压缩比

from PIL import Image
import os

LZW
string = input("输入需要的编码的字符串:")
dictionary = {chr(i):i for i in range(32, 122)}

last = 256
p = ""
result = []

for c in string:
    pc = p + c
    if pc in dictionary:
        p = pc
    else:
        result.append(dictionary[p])
        dictionary[pc] = last
        last += 1
        p = c
if p != '':
    result.append(dictionary[p])

print(result)

#求压缩比
j = len(string)
k = len(result)
n = (9*k)/(8*j)
print("压缩比:",n)

压缩图像


from PIL import Image
import os

def get_size(file):
  # 获取文件大小:KB
  size = os.path.getsize(file)
  return size / 1024
def get_outfile(infile, outfile):
  if outfile:
    return outfile
  dir, suffix = os.path.splitext(infile)
  # print(dir,suffix)
  outfile = '{}-out{}'.format(dir, '.png')
  return outfile
def compress_image(infile, outfile='', mb=150, step=10, quality=80):
  # 不改变图片尺寸压缩到指定大小
  # :param infile: 压缩源文件
  # :param outfile: 压缩文件保存地址
  # :param mb: 压缩目标,KB
  # :param step: 每次调整的压缩比率
  # :param quality: 初始压缩比率
  # :return: 压缩文件地址,压缩文件大小

  o_size = get_size(infile)
  if o_size <= mb:
    return infile
  outfile = get_outfile(infile, outfile)
  while o_size > mb:
    im = Image.open(infile)
    im.save(outfile, quality=quality)
    if quality - step < 0:
      break
    quality -= step
    o_size = get_size(outfile)
  return outfile, get_size(outfile)

if __name__ == '__main__':
  compress_image(r'fog1.bmp')

压缩编码

dictionary = {i: chr(i) for i in range(97, 123)}
last = 256
arr = [97, 97, 98, 256, 258, 257, 259]

result = []
p = arr.pop(0)
result.append(dictionary[p])

for c in arr:
  if c in dictionary:
    entry = dictionary[c]
  result.append(entry)
  dictionary[last] = dictionary[p] + entry[0]
  last += 1
  p = c
print(''.join(result))

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值