Skip to content

Commit 6394d1d

Browse files
committed
update
1 parent 270baa9 commit 6394d1d

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/JpegEncoder/jpeg_encoder.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
#
44
# 这是一个灰度图像的 JPEG 压缩算法。
55
# 它不调用除了 numpy 以外的任何库,完整而简洁地展示了 JPEG 算法的原理。
6+
# 简单起见,本代码只支持长和宽为 8 的倍数的图象,尽管 JPEG 标准支持长和宽不为 8 的倍数的图象。
67
#
7-
# 另外为了进行测试,它还调用了 PIL.Image 库用来读取待压缩的原始文件,但在JPEG 压缩算法中没用 PIL.Image 库。
8+
# 另外为了进行测试,它还调用了 PIL.Image 库用来读取待压缩的原始文件,但在JPEG 压缩算法中完全不使用 PIL.Image 库。
89
#
910
# 你可以用它来进行图像图像压缩,比如,运行以下命令可以把 image.pgm (原始像素文件) 压缩成 image.jpg (JPEG压缩文件) 。
1011
# python JpegEncoder.py image.pgm image.jpg
@@ -16,6 +17,7 @@
1617
import numpy as np
1718
from PIL.Image import open as imgopen
1819

20+
1921
class BitstreamWriter():
2022
def __init__(self):
2123
self.bitpos = 7
@@ -44,6 +46,7 @@ def flush(self):
4446
def get(self):
4547
return self.stream
4648

49+
4750
dct_mat = np.matrix( [
4851
[ 32, 32, 32, 32, 32, 32, 32, 32],
4952
[ 44, 38, 25, 9, -9,-25,-38,-44],
@@ -64,6 +67,7 @@ def get(self):
6467
[21,34,37,47,50,56,59,61],
6568
[35,36,48,49,57,58,62,63] ], dtype = np.int32 )
6669

70+
6771
def shift_round_clip(x):
6872
y = np.int8(x>>16)
6973
if x>>15 & 0x1:
@@ -74,6 +78,7 @@ def shift_round_clip(x):
7478
y = -63
7579
return y
7680

81+
7782
def dct_quant_zig(tile): # input tile must be (8*8)
7883
tile = np.matrix(tile, dtype=np.int32)
7984
zig_vect = np.zeros((64,), dtype=np.int8)
@@ -85,6 +90,7 @@ def dct_quant_zig(tile): # input tile must be (8*8)
8590
zig_vect[pos] = shift_round_clip( dct_tile[i,j] >> quant_level )
8691
return zig_vect
8792

93+
8894
def get_code(val):
8995
absval = val if val>=0 else -val
9096
length = 0
@@ -94,6 +100,7 @@ def get_code(val):
94100
code = val if val>=0 else (val-1)
95101
return length, code
96102

103+
97104
def bit_encoding(stream_writer, zig_vect):
98105
zero_cnt = 0
99106
for ii, val in enumerate(zig_vect):
@@ -107,6 +114,7 @@ def bit_encoding(stream_writer, zig_vect):
107114
elif ii==63:
108115
stream_writer.writebits( 0x0f, 8 )
109116

117+
110118
def jpeg_encoding(img_map): # img_map must be a 2-dim numpy array, and has a height and width which can divide 8
111119
h, w = img_map.shape
112120
JpegStreamWriter = BitstreamWriter()

0 commit comments

Comments
 (0)