BIT 数字图像处理 编程作业2:LZW编码

在这里插入图片描述

问题描述(Description)
Lempel-Ziv-Welch(LZW)编码算法是一种无误差压缩算法,将定长码字分配给变长信源符号序列。 现请尝试对输入单张灰度图像进行LZW编码。

输入(Input)
输入格式如下面的例子所示。

第一行为两个由空格隔开的数字M和N,分别代表图片的高和宽。

接下来M行,每行有N个数字,每个数字代表图片相应位置的灰度值,相邻的数字由空格隔开。

读取数据时要求以行优先的方式读取。

例:

4 4

39 39 126 126

39 39 126 126

39 39 126 126

39 39 126 126

输出(Output)
图片的LZW编码,相邻的码字用空格隔开。

#include <iostream> 
#include <vector> 
#include <iomanip> 
#include <limits> 
#include <math.h> 
#include <map> 
#include <string> 
 
using namespace std; 
 
void showImage(vector<vector<string>> &image_2d) 
{ 
    for (int i = 0; i < image_2d.size(); i++) 
    { 
        for (int j = 0; j < image_2d[0].size(); j++) 
            // 访问并且输出(左对齐)二维矩阵的各个元素 
            cout << image_2d[i][j] << " "; 
        cout << endl; 
    } 
} 
 
void showCode(vector<int> &code) 
{ 
    for (int i = 0; i < code.size(); i++) 
    { 
        cout << code[i] << " "; 
    } 
    cout << endl; 
} 
 
static vector<int> encode() 
{ 
    //初始化dictionary 
    int m, n; 
    int value; 
    cin >> m >> n; 
    int idleCode = 256; 
    map<string, int> dictionary; 
    for (int i = 0; i < idleCode; i++) 
    { 
        dictionary.insert(pair<string, int>(to_string(i), i)); 
    } 
    string P = ""; 
    string C = ""; 
    string PC = ""; 
    bool PC_in_dic = true; 
    vector<int> result = result; 
    for (int i = 0; i < m; i++) 
    { 
        for (int j = 0; j < n; j++) 
        { 
            cin >> value; 
            C = to_string(value); 
            if (P.size()) 
            { 
                PC = P + "-" + C; 
            } 
            else 
            { 
                PC = C; 
            } 
             
            // 操作 
            if (dictionary.count(PC)) 
            { 
                P = PC; 
                // cout << "-[INFO] Yes, P=" << P << endl; 
            } 
            else 
            { 
                dictionary.insert(pair<string, int>(PC, idleCode)); 
                idleCode += 1; 
                result.push_back(dictionary[P]); 
                P = C; 
                // cout << "-[INFO] No, P+C=" << PC << endl; 
            } 
        } 
    } 
    result.push_back(dictionary[P]); 
    return result; 
} 
 
int main() 
{ 
    vector<int> result; 
    result = encode(); 
    // cout << "Result:" << endl; 
    showCode(result); 
    return 0; 
} 
 
/* 
4 4 
39 39 126 126 
39 39 126 126 
39 39 126 126 
39 39 126 126 
 
39 39 126 126 256 258 260 259 257 126 
39 39 126 126 256 258 260 259 257 126 
*/  

在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BIT可达鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值