Implement basic image compression with discrete cosine transform from scratch like JPEG. Break images into 8x8 blocks, apply DCT, quantize coefficients, and visualize the blockiness vs size trade-off by adjusting the quantization table.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The plan covers implementing 8x8 block DCT and inverse via precomputed orthonormal matrices, scaling JPEG quantization tables by quality factors, quantizing/dequantizing blocks, reconstructing grayscale images, and approximating compressed size by counting non-zero quantized coefficients. Next, I'll implement these steps in Python with numpy and PIL along with visualization of quality vs blockiness.
Below is a self–contained example in Python that implements the core steps of a JPEG‑like pipeline “from scratch” on a grayscale image:
split the image into 8×8 blocks
apply a 2‑D DCT
quantize the coefficients using a luminance quantization table scaled by a “quality” factor
dequantize, apply the inverse DCT, and reconstruct the image
For convenience we count the number of non‑zero quantized coefficients as a crude proxy for “compressed size” and visualize the reconstruction quality for different quantization strengths.
python
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# JPEG standard luminance quantization table
JPEG_Q_Y = np.array([
[16, 11, 10, 16, 24, 40, 51, 61],
[12, 12, 14, 19, 26, 58, 60, 55],
[14, 13, 16, 24, 40, 57, 69, 56],
[14, 17, 22, 29, 51, 87, 80, 62],
[18, 22, 37, 56, 68, 109, 103, 77],
[24, 35, 55, 64, 81, 104, 113, 92],
[49, 64, 78, 87,103, 121, 120, 101],
[72, 92, 95, 98,112, 100, 103, 99]
], dtype=np.float32)
def quality_scale_table(base_table, quality):
"""Scale the base quantization table according to JPEG quality factor (1–100)."""
q = np.clip(quality, 1, 100)
if q < 50:
scale = 5000 / q
else:
scale = 200 - 2 * q
table = np.floor((base_table * scale + 50) / 100)
table[table == 0] = 1 # quantization values must be >=1
return table
def dct_matrix(N=8):
"""Compute the NxN DCT (type II) transform matrix."""
T = np.zeros((N, N))
for u in range(N):
for x in range(N):
alpha = np.sqrt(1/N) if u == 0 else np.sqrt(2/N)
T[u, x] = alpha * np.cos((np.pi*(2*x+1)*u) / (2*N))
return T
T8 = dct_matrix(8)
def block_process(img, func):
"""Apply a function to each 8x8 block of the image."""
h, w = img.shape
out = np.zeros_like(img, dtype=np.float32)
for i in range(0, h, 8):
for j in range(0, w, 8):
block = img[i:i+8, j:j+8]
out[i:i+8, j:j+8] = func(block)
return out
def compress(img, q_table):
"""Forward DCT + quantization."""
# center pixel values around zero
img_shifted = img.astype(np.float32) - 128.0
def fwd(block):
dct_block = T8 @ block @ T8.T
return np.round(dct_block / q_table)
coeffs = block_process(img_shifted, fwd)
return coeffs
def decompress(coeffs, q_table):
"""Dequantize + inverse DCT."""
def inv(block):
deq = block * q_table
return T8.T @ deq @ T8
rec = block_process(coeffs, inv)
rec = rec + 128.0
return np.clip(np.round(rec), 0, 255).astype(np.uint8)
# Load an example image and convert to grayscale, pad to multiple of 8
img = Image.open('your_image.jpg').convert('L')
img_np = np.array(img, dtype=np.uint8)
h, w = img_np.shape
# pad if necessary
pad_h = (8 - h % 8) % 8
pad_w = (8 - w % 8) % 8
img_np = np.pad(img_np, ((0, pad_h), (0, pad_w)), mode='edge')
qualities = [20, 40, 60, 80, 95]
recons = []
nz_counts = []
for q in qualities:
qtable = quality_scale_table(JPEG_Q_Y, q)
coeffs = compress(img_np, qtable)
recons.append(decompress(coeffs, qtable))
nz_counts.append(np.count_nonzero(coeffs))
# Plot original and reconstructions
plt.figure(figsize=(12, 6))
plt.subplot(2, len(qualities)+1, 1)
plt.imshow(img_np, cmap='gray')
plt.title('Original')
plt.axis('off')
for idx, (q, rec, nz) in enumerate(zip(qualities, recons, nz_counts), start=2):
plt.subplot(2, len(qualities)+1, idx)
plt.imshow(rec, cmap='gray')
plt.title(f'Q={q}\nNZ coeffs={nz}')
plt.axis('off')
# Plot blockiness detail (zoom into a region)
zoom = (50, 50, 130, 130) # y0, x0, y1, x1
y0, x0, y1, x1 = zoom
plt.subplot(2, len(qualities)+1, len(qualities)+2)
plt.imshow(img_np[y0:y1, x0:x1], cmap='gray')
plt.title('Original (zoom)')
plt.axis('off')
for idx, rec in enumerate(recons, start=len(qualities)+3):
plt.subplot(2, len(qualities)+1, idx)
plt.imshow(rec[y0:y1, x0:x1], cmap='gray', vmin=0, vmax=255)
plt.title(f'Q={qualities[idx-len(qualities)-3]} (zoom)')
plt.axis('off')
plt.tight_layout()
plt.show()
A few notes:
The quality factor ranges from 1 (very coarse quantization, lots of blockiness) to 100 (minimal quantization). The quality_scale_table scales the base JPEG luminance quantization matrix accordingly.
The non‑zero coefficient count drops as you lower the quality, indicating fewer bits would be needed to encode the image. This is a crude proxy; real JPEG uses run‑length and entropy coding on the zig‑zag–ordered coefficients.
For simplicity this example operates on a single luminance channel. Extending it to RGB is straightforward: apply the same steps per channel or convert to YCbCr and use different quantization tables per component.
Running the script will show how the reconstructed image degrades (visible blockiness) as you increase quantization and how the “compressed size” proxy changes.