黃駿棠
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- title: 'CS362 Assignment #6' disqus: hackmd --- Run-Length Based Image Compression 練習 === ## 目錄 [TOC] ## 作業說明 附件中為三張利用將晶片高度以色彩視覺化後的圖片。 請設計一個基於Run-Length 的壓縮法方,對圖檔作無失真壓縮後儲存成新檔案。 部落格上應敘述你的壓縮方法,提供壓縮檔之格式,並計算三張圖的平均壓縮率。 | Table1 |Image 1| Image 2| Image 3| |:--:|:--:|:--:|:--:| |預覽| ![](https://hackmd.io/_uploads/HyvOG9YU3.png =300x180) | ![](https://hackmd.io/_uploads/H1YdM5YLh.png =300x180)| ![](https://hackmd.io/_uploads/rksOG5tUh.png =300x180) | ## 開發環境 ```bash $ uname -srvmio Linux 5.15.90.1-microsoft-standard-WSL2 #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 x86_64 GNU/Linux $ gcc --version gcc (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0 ``` ## 實作方式 1. 讀入檔案 2. 因為三個檔案的標頭相同因此可以移除54 byte內容 3. 透過zigzag重排資料 4. 透過run-length進行壓縮 5. 反向解壓縮解碼 6. 用diff比較結果 ## 程式碼說明 #### 標頭檔 ```cpp=1 #include <iostream> #include <string> #include <vector> #include <fstream> ``` #### 編譯器指令 ```cpp=+ // Disable alignment for struct (讓編譯器不要自動對齊) #pragma pack(1) ``` #### Namespace & Prototype 宣告 ```cpp=7 using namespace std; vector<char> zigZagEncode(const std::vector<char>& input); vector<char> zigZagDecode(const std::vector<char>& input); ``` #### BMP Header定義 ```cpp=+ struct BMPHeader { char signature[2] = {0x42, 0x4d}; uint32_t fileSize = 14665254; uint32_t reserved = 0; uint32_t dataOffset = 54; uint32_t headerSize = 40; int32_t width = 2420; int32_t height = 2020; uint16_t planes = 1; uint16_t bitDepth = 24; uint32_t compression = 0; uint32_t imageSize = 0; int32_t xPixelsPerMeter = 0; int32_t yPixelsPerMeter = 0; uint32_t colorsUsed = 0; uint32_t colorsImportant = 0; } bmpHeader; ``` #### 主程式 ```cpp=+ int main(int argc, char* argv[] ) { for(auto i = 1; i < argc; i++) { // Open file fstream infile; infile.open(argv[i], ios::binary | ios::in); if(!infile) { cout << "Cannot open file: "<< argv[i] << endl; continue; } // Read file int dataSize = bmpHeader.fileSize - bmpHeader.dataOffset; vector<char> pixelData(dataSize); infile.seekg(bmpHeader.dataOffset, std::ios::beg); for(int j = 0; j < dataSize; j++) { infile.read(&pixelData[j], sizeof(char)); } infile.close(); // ZigZag encoding cout << "encoding...\n"; pixelData = zigZagEncode(pixelData); cout << "size: " << pixelData.size() << endl; // Run-length Compress cout << "compressing...\n"; vector<char> outputData; int count = 1; for(int j = 0; j < pixelData.size(); j++) { char temp = pixelData[j]; if(temp == pixelData[j+1] && count <= 255) { count++; } else { outputData.push_back(temp); outputData.push_back(count); count = 1; } } cout << "size: " << outputData.size() << endl; // Write output binary file fstream outfile; string outFileName = "output_" + string(argv[i]) + ".bin"; outfile.open(outFileName, ios::binary | ios::out); outfile.write(&(outputData[0]), outputData.size()); outfile.close(); // Read output binary file cout << "Loading bin file...\n"; fstream infile2; infile2.open(outFileName, ios::binary | ios::in); if(!infile2) { cout << "Cannot open file: "<< outFileName << endl; continue; } // Get file size infile2.seekg(0, ios::end); int dataSize2 = infile2.tellg(); infile2.seekg(0, ios::beg); cout << "size: " << dataSize2 << endl; cout << "Uncompressing...\n"; // Read file vector<char> inputData2(dataSize2); infile2.seekg(0, std::ios::beg); for(int j = 0; j < dataSize2; j++) { infile2.read(&inputData2[j], sizeof(char)); } infile2.close(); vector<char> pixelData2(pixelData.size()); int j = 0, index = 0 ; while(j < inputData2.size()) { char temp = inputData2[j++]; int count = (uint)inputData2[j++]; for(int k =0; k < count; k++) pixelData2[index++] = temp; } cout << "size: " << pixelData2.size() << endl; pixelData2 = zigZagDecode(pixelData2); fstream outfile2; string outFileName2 = "output_rev_" + string(argv[i]); outfile2.open(outFileName2, ios::binary | ios::out); outfile2.write(reinterpret_cast<char*>(&bmpHeader), sizeof(bmpHeader)); outfile2.write(&(pixelData2[0]), pixelData2.size()); outfile2.close(); } return 0; } ``` #### ZigZag Encode & Decode ```cpp=+ vector<char> zigZagEncode(const std::vector<char>& input) { vector<char> output; int numColumns = 16; int numRows = input.size() / numColumns; int i = 0, j = 0; bool up = true; while (i < numRows && j < numColumns) { output.push_back(input[i * numColumns + j]); if (up) { if (i == 0) { up = false; j++; } else if (j == numColumns - 1) { up = false; i++; } else { i--; j++; } } else { if (j == 0) { up = true; i++; } else if (i == numRows - 1) { up = true; j++; } else { i++; j--; } } } return output; } vector<char> zigZagDecode(const std::vector<char>& input) { vector<char> output(input.size()); int numColumns = 16; int numRows = input.size() / numColumns; int i = 0, j = 0; bool up = true; int index = 0; while (index < input.size()) { output[i * numColumns + j] = input[index]; if (up) { if (i == 0) { up = false; j++; } else if (j == numColumns - 1) { up = false; i++; } else { i--; j++; } } else { if (j == 0) { up = true; i++; } else if (i == numRows - 1) { up = true; j++; } else { i++; j--; } } index++; } return output; } ``` ## 編譯與執行 ### 編譯 ```bash= g++ image_compress.cpp ``` ### 執行程式 ```bash=+ ./a.out img1.bmp img2.bmp img3.bmp ``` ![](https://hackmd.io/_uploads/Bk1beoKLn.png) ### 比對結果 ```bash=+ diff img1.bmp output_rev_img1.bmp diff img2.bmp output_rev_img2.bmp diff img3.bmp output_rev_img3.bmp ``` #### 壓縮檔案(output_rev_xxxx.bmp)還原後和原始檔案大小一致 ![](https://hackmd.io/_uploads/B19VloY8n.png) #### 透過diff比對內容結果一致 ![](https://hackmd.io/_uploads/Sy57xjY82.png) ### 壓縮率計算 | Table2 | Image 1| Image 2| Image 3| |:--:|:--:|:--:|:--:| |原始圖片| ![](https://hackmd.io/_uploads/HyvOG9YU3.png =300x180) | ![](https://hackmd.io/_uploads/H1YdM5YLh.png =300x180)| ![](https://hackmd.io/_uploads/rksOG5tUh.png =300x180) | |原始大小|14665254|14665254|14665254| |壓縮大小|6928092|8319702|6917278| |壓縮率|211.68%|176.27%|212.01%| 平均壓縮率:(14665254*3)/(6928092+8319702+6917278) * 100% = 198.49% ## 參考資料 - [BMP Header](https://zh.wikipedia.org/zh-tw/BMP) - [ZigZag](https://www.uoanbar.edu.iq/eStoreImages/Bank/6137.pdf) ###### tags: `CS362` `s1081050` `HW6`

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully