Huffman kompresijas algoritms

Pirms kursa sākuma "Algoritmi izstrādātājiem" sagatavoja jums cita noderīga materiāla tulkojumu.

Huffman kodÄ“Å”ana ir datu saspieÅ”anas algoritms, kas formulē failu saspieÅ”anas pamatideju. Å ajā rakstā mēs runāsim par fiksēta un mainÄ«ga garuma kodÄ“Å”anu, unikāli dekodējamiem kodiem, prefiksu kārtulām un Hafmena koka izveidi.

Mēs zinām, ka katra rakstzÄ«me tiek saglabāta kā 0 un 1 secÄ«ba un aizņem 8 bitus. To sauc par fiksēta garuma kodējumu, jo katra rakstzÄ«me saglabāŔanai izmanto tādu paÅ”u fiksētu bitu skaitu.

Pieņemsim, ka mums ir dots teksts. Kā mēs varam samazināt vietas daudzumu, kas nepiecieÅ”ams vienas rakstzÄ«mes glabāŔanai?

Galvenā ideja ir mainÄ«ga garuma kodÄ“Å”ana. Mēs varam izmantot faktu, ka dažas rakstzÄ«mes tekstā parādās biežāk nekā citas (skatÄ«t Å”eit), lai izstrādātu algoritmu, kas attēlos to paÅ”u rakstzÄ«mju secÄ«bu mazākos bitos. MainÄ«ga garuma kodējumā mēs pieŔķiram rakstzÄ«mēm mainÄ«gu bitu skaitu atkarÄ«bā no tā, cik bieži tās parādās konkrētajā tekstā. Galu galā dažas rakstzÄ«mes var aizņemt tikai 1 bitu, bet citas var aizņemt 2 bitus, 3 vai vairāk. Problēma ar mainÄ«ga garuma kodÄ“Å”anu ir tikai sekojoŔā secÄ«bas dekodÄ“Å”ana.

Kā, zinot bitu secÄ«bu, to viennozÄ«mÄ«gi atÅ”ifrēt?

Apsveriet lÄ«niju "abacdab". Tam ir 8 rakstzÄ«mes, un, kodējot fiksētu garumu, tā glabāŔanai bÅ«s nepiecieÅ”ami 64 biti. Ņemiet vērā, ka simbolu biežums "a", "b", "c" Šø "D" ir vienāds ar attiecÄ«gi 4, 2, 1, 1. Mēģināsim iedomāties "abacdab" mazāk bitu, izmantojot faktu, ka "uz" notiek biežāk nekā "B"Un "B" notiek biežāk nekā "c" Šø "D". Sāksim ar kodÄ“Å”anu "uz" ar vienu bitu, kas vienāds ar 0, "B" mēs pieŔķirsim divu bitu kodu 11, un, izmantojot trÄ«s bitus 100 un 011, mēs kodēsim "c" Šø "D".

Rezultātā mēs iegūsim:

a
0

b
11

c
100

d
011

Tātad lÄ«nija "abacdab" mēs iekodēsim kā 00110100011011 (0|0|11|0|100|011|0|11)izmantojot iepriekÅ” minētos kodus. Tomēr galvenā problēma bÅ«s dekodÄ“Å”ana. Kad mēs cenÅ”amies atÅ”ifrēt virkni 00110100011011, mēs iegÅ«stam neviennozÄ«mÄ«gu rezultātu, jo to var attēlot Ŕādi:

0|011|0|100|011|0|11    adacdab
0|0|11|0|100|0|11|011   aabacabd
0|011|0|100|0|11|0|11   adacabab 

...
uc

Lai izvairÄ«tos no Ŕīs neskaidrÄ«bas, mums ir jānodroÅ”ina, lai mÅ«su kodējums atbilstu tādam jēdzienam kā prefiksa noteikums, kas savukārt nozÄ«mē, ka kodus var atÅ”ifrēt tikai vienā unikālā veidā. Prefiksa noteikums nodroÅ”ina, ka neviens kods nav cita prefikss. Ar kodu mēs saprotam bitus, ko izmanto, lai attēlotu noteiktu rakstzÄ«mi. IepriekÅ” minētajā piemērā 0 ir prefikss 011, kas pārkāpj prefiksa noteikumu. Tātad, ja mÅ«su kodi atbilst prefiksa likumam, mēs varam unikāli atÅ”ifrēt (un otrādi).

ApskatÄ«sim iepriekÅ” minēto piemēru. Å oreiz mēs pieŔķirsim simboliem "a", "b", "c" Šø "D" kodi, kas atbilst prefiksa noteikumam.

a
0

b
10

c
110

d
111

Izmantojot Å”o kodējumu, virkne "abacdab" tiks kodēts kā 00100100011010 (0|0|10|0|100|011|0|10). Bet 00100100011010 mēs jau varēsim viennozÄ«mÄ«gi atÅ”ifrēt un atgriezties pie savas sākotnējās virknes "abacdab".

Hafmena kodēŔana

Tagad, kad esam tikuÅ”i galā ar mainÄ«ga garuma kodējumu un prefiksa noteikumu, parunāsim par Hafmena kodējumu.

Metodes pamatā ir bināro koku izveide. Tajā mezgls var bÅ«t gan galÄ«gs, gan iekŔējs. Sākotnēji visi mezgli tiek uzskatÄ«ti par lapām (termināļiem), kas attēlo paÅ”u simbolu un tā svaru (tas ir, parādÄ«Å”anās biežumu). IekŔējie mezgli satur rakstzÄ«mes svaru un attiecas uz diviem pēcnācējiem. Pēc vispārējas vienoÅ”anās, bit Ā«0Ā» apzÄ«mē sekoÅ”anu kreisajam zaram un Ā«1Ā» - pa labi. pilnā kokā N lapas un N-1 iekŔējie mezgli. Veidojot Hafmena koku, neizmantotos simbolus ieteicams izmest, lai iegÅ«tu optimālus garuma kodus.

Mēs izmantosim prioritāro rindu, lai izveidotu Huffman koku, kur mezglam ar zemāko frekvenci tiks pieŔķirta augstākā prioritāte. BÅ«vniecÄ«bas soļi ir aprakstÄ«ti zemāk:

  1. Katrai rakstzīmei izveidojiet lapas mezglu un pievienojiet to prioritārajai rindai.
  2. Kamēr rindā ir vairāk nekā viena lapa, rÄ«kojieties Ŕādi:
    • Noņemiet no rindas divus mezglus ar augstāko prioritāti (zemāko frekvenci);
    • Izveidojiet jaunu iekŔējo mezglu, kur Å”ie divi mezgli bÅ«s bērni, un raÅ”anās biežums bÅ«s vienāds ar Å”o divu mezglu frekvenču summu.
    • Pievienojiet jaunu mezglu prioritārajai rindai.
  3. Vienīgais atlikuŔais mezgls būs sakne, un tas pabeigs koka būvniecību.

Iedomājieties, ka mums ir kāds teksts, kas sastāv tikai no rakstzÄ«mēm "a", "b", "c", "d" Šø "un", un to sastopamÄ«bas biežums ir attiecÄ«gi 15, 7, 6, 6 un 5. Zemāk ir ilustrācijas, kas atspoguļo algoritma darbÄ«bas.

Huffman kompresijas algoritms

Huffman kompresijas algoritms

Huffman kompresijas algoritms

Huffman kompresijas algoritms

Huffman kompresijas algoritms

Ceļā no saknes uz jebkuru gala mezglu tiks saglabāts optimālais prefiksa kods (pazīstams arī kā Hafmena kods), kas atbilst ar Ŕo gala mezglu saistītajai rakstzīmei.

Huffman kompresijas algoritms
Huffman koks

Zemāk jūs atradīsit Huffman saspieŔanas algoritma ievieŔanu C++ un Java:

#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;

// A Tree node
struct Node
{
	char ch;
	int freq;
	Node *left, *right;
};

// Function to allocate a new tree node
Node* getNode(char ch, int freq, Node* left, Node* right)
{
	Node* node = new Node();

	node->ch = ch;
	node->freq = freq;
	node->left = left;
	node->right = right;

	return node;
}

// Comparison object to be used to order the heap
struct comp
{
	bool operator()(Node* l, Node* r)
	{
		// highest priority item has lowest frequency
		return l->freq > r->freq;
	}
};

// traverse the Huffman Tree and store Huffman Codes
// in a map.
void encode(Node* root, string str,
			unordered_map<char, string> &huffmanCode)
{
	if (root == nullptr)
		return;

	// found a leaf node
	if (!root->left && !root->right) {
		huffmanCode[root->ch] = str;
	}

	encode(root->left, str + "0", huffmanCode);
	encode(root->right, str + "1", huffmanCode);
}

// traverse the Huffman Tree and decode the encoded string
void decode(Node* root, int &index, string str)
{
	if (root == nullptr) {
		return;
	}

	// found a leaf node
	if (!root->left && !root->right)
	{
		cout << root->ch;
		return;
	}

	index++;

	if (str[index] =='0')
		decode(root->left, index, str);
	else
		decode(root->right, index, str);
}

// Builds Huffman Tree and decode given input text
void buildHuffmanTree(string text)
{
	// count frequency of appearance of each character
	// and store it in a map
	unordered_map<char, int> freq;
	for (char ch: text) {
		freq[ch]++;
	}

	// Create a priority queue to store live nodes of
	// Huffman tree;
	priority_queue<Node*, vector<Node*>, comp> pq;

	// Create a leaf node for each character and add it
	// to the priority queue.
	for (auto pair: freq) {
		pq.push(getNode(pair.first, pair.second, nullptr, nullptr));
	}

	// do till there is more than one node in the queue
	while (pq.size() != 1)
	{
		// Remove the two nodes of highest priority
		// (lowest frequency) from the queue
		Node *left = pq.top(); pq.pop();
		Node *right = pq.top();	pq.pop();

		// Create a new internal node with these two nodes
		// as children and with frequency equal to the sum
		// of the two nodes' frequencies. Add the new node
		// to the priority queue.
		int sum = left->freq + right->freq;
		pq.push(getNode('', sum, left, right));
	}

	// root stores pointer to root of Huffman Tree
	Node* root = pq.top();

	// traverse the Huffman Tree and store Huffman Codes
	// in a map. Also prints them
	unordered_map<char, string> huffmanCode;
	encode(root, "", huffmanCode);

	cout << "Huffman Codes are :n" << 'n';
	for (auto pair: huffmanCode) {
		cout << pair.first << " " << pair.second << 'n';
	}

	cout << "nOriginal string was :n" << text << 'n';

	// print encoded string
	string str = "";
	for (char ch: text) {
		str += huffmanCode[ch];
	}

	cout << "nEncoded string is :n" << str << 'n';

	// traverse the Huffman Tree again and this time
	// decode the encoded string
	int index = -1;
	cout << "nDecoded string is: n";
	while (index < (int)str.size() - 2) {
		decode(root, index, str);
	}
}

// Huffman coding algorithm
int main()
{
	string text = "Huffman coding is a data compression algorithm.";

	buildHuffmanTree(text);

	return 0;
}

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

// A Tree node
class Node
{
	char ch;
	int freq;
	Node left = null, right = null;

	Node(char ch, int freq)
	{
		this.ch = ch;
		this.freq = freq;
	}

	public Node(char ch, int freq, Node left, Node right) {
		this.ch = ch;
		this.freq = freq;
		this.left = left;
		this.right = right;
	}
};

class Huffman
{
	// traverse the Huffman Tree and store Huffman Codes
	// in a map.
	public static void encode(Node root, String str,
							  Map<Character, String> huffmanCode)
	{
		if (root == null)
			return;

		// found a leaf node
		if (root.left == null && root.right == null) {
			huffmanCode.put(root.ch, str);
		}


		encode(root.left, str + "0", huffmanCode);
		encode(root.right, str + "1", huffmanCode);
	}

	// traverse the Huffman Tree and decode the encoded string
	public static int decode(Node root, int index, StringBuilder sb)
	{
		if (root == null)
			return index;

		// found a leaf node
		if (root.left == null && root.right == null)
		{
			System.out.print(root.ch);
			return index;
		}

		index++;

		if (sb.charAt(index) == '0')
			index = decode(root.left, index, sb);
		else
			index = decode(root.right, index, sb);

		return index;
	}

	// Builds Huffman Tree and huffmanCode and decode given input text
	public static void buildHuffmanTree(String text)
	{
		// count frequency of appearance of each character
		// and store it in a map
		Map<Character, Integer> freq = new HashMap<>();
		for (int i = 0 ; i < text.length(); i++) {
			if (!freq.containsKey(text.charAt(i))) {
				freq.put(text.charAt(i), 0);
			}
			freq.put(text.charAt(i), freq.get(text.charAt(i)) + 1);
		}

		// Create a priority queue to store live nodes of Huffman tree
		// Notice that highest priority item has lowest frequency
		PriorityQueue<Node> pq = new PriorityQueue<>(
										(l, r) -> l.freq - r.freq);

		// Create a leaf node for each character and add it
		// to the priority queue.
		for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
			pq.add(new Node(entry.getKey(), entry.getValue()));
		}

		// do till there is more than one node in the queue
		while (pq.size() != 1)
		{
			// Remove the two nodes of highest priority
			// (lowest frequency) from the queue
			Node left = pq.poll();
			Node right = pq.poll();

			// Create a new internal node with these two nodes as children 
			// and with frequency equal to the sum of the two nodes
			// frequencies. Add the new node to the priority queue.
			int sum = left.freq + right.freq;
			pq.add(new Node('', sum, left, right));
		}

		// root stores pointer to root of Huffman Tree
		Node root = pq.peek();

		// traverse the Huffman tree and store the Huffman codes in a map
		Map<Character, String> huffmanCode = new HashMap<>();
		encode(root, "", huffmanCode);

		// print the Huffman codes
		System.out.println("Huffman Codes are :n");
		for (Map.Entry<Character, String> entry : huffmanCode.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}

		System.out.println("nOriginal string was :n" + text);

		// print encoded string
		StringBuilder sb = new StringBuilder();
		for (int i = 0 ; i < text.length(); i++) {
			sb.append(huffmanCode.get(text.charAt(i)));
		}

		System.out.println("nEncoded string is :n" + sb);

		// traverse the Huffman Tree again and this time
		// decode the encoded string
		int index = -1;
		System.out.println("nDecoded string is: n");
		while (index < sb.length() - 2) {
			index = decode(root, index, sb);
		}
	}

	public static void main(String[] args)
	{
		String text = "Huffman coding is a data compression algorithm.";

		buildHuffmanTree(text);
	}
}

PiezÄ«me: atmiņa, ko izmanto ievades virkne, ir 47 * 8 = 376 biti, un kodētā virkne ir tikai 194 biti, t.i. dati tiek saspiesti par aptuveni 48%. IepriekÅ” minētajā C++ programmā mēs izmantojam virkņu klasi, lai saglabātu kodēto virkni, lai programma bÅ«tu lasāma.

Tā kā efektīvai prioritāro rindu datu struktūrām ir nepiecieŔama katra ievietoŔana O(log(N)) laikā, bet pilnīgā binārā kokā ar N lapas klāt 2N-1 mezgliem, un Hafmena koks ir pilnīgs binārs koks, tad tiek palaists algoritms O(Nlog(N)) laiks, kur N - Personāži.

Avoti:

en.wikipedia.org/wiki/Huffman_coding
en.wikipedia.org/wiki/Variable-length_code
www.youtube.com/watch?v=5wRPin4oxCo

Uzziniet vairāk par kursu.

Avots: www.habr.com

Pievieno komentāru