{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ff978c45",
   "metadata": {},
   "source": [
    "# TP3- Differential Pulse-Code Modulation (DPCM)\n",
    "\n",
    "## Objectifs\n",
    "\n",
    "To understand and implement Differential Pulse-Code Modulation (DPCM), study lossless and lossy predictive coding, compare open-loop versus closed-loop prediction, analyze quantization effects, and compute error metrics such as MSE and PSNR.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69bbb737",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "image1 = \"image_1_grayscale.jpg\"\n",
    "image2 = \"image_2_colored.jpg\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c90ea74",
   "metadata": {},
   "source": [
    "## Part 1: Lossless DPCM on Image Data\n",
    "\n",
    "### Step I — Linear Representation of Image Data\n",
    "\n",
    "Convert a 2D grayscale image matrix into a 1D sequence by **flattening** rows in raster-scan order. This representation enables sequential predictive processing.\n",
    "\n",
    "### Step II — Inverse Linear Representation\n",
    "\n",
    "Reconstruct the original 2D image by reshaping the 1D linear sequence back into its height \\* width structure.\n",
    "\n",
    "### Step III — Lossless DPCM Encoding\n",
    "\n",
    "**Lossless DPCM** reduces redundancy using a simple predictor.\n",
    "The **prediction** is:\n",
    "\n",
    "$$\n",
    "\\hat{x}_n = x_{n-1}\n",
    "$$\n",
    "\n",
    "The difference signal is:\n",
    "\n",
    "$$\n",
    "d_n = x_n - \\hat{x}_n\n",
    "$$\n",
    "\n",
    "The first sample must be transmitted explicitly since it has no predictor.\n",
    "\n",
    "### Step IV — Lossless DPCM Decoding\n",
    "\n",
    "Reconstruction is performed by summing the previous reconstructed value with the **difference**:\n",
    "\n",
    "$$\n",
    "\\tilde{x}_n = \\tilde{x}_{n-1} + d_n\n",
    "$$\n",
    "\n",
    "This results in perfect reconstruction.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f34e4c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Step 1: Flatten the image into a 1D sequence\n",
    "def image_to_sequence(image):\n",
    "    # Convert to int16 to safely handle differences (negative values)\n",
    "    return image.astype(np.int16).flatten()\n",
    "\n",
    "\n",
    "# Step 2: Reconstruct the image from the 1D sequence\n",
    "def sequence_to_image(sequence, shape):\n",
    "    # Clip to valid range and convert back to uint8 for display/saving\n",
    "    sequence = np.clip(sequence, 0, 255).astype(np.uint8)\n",
    "    return sequence.reshape(shape)\n",
    "\n",
    "\n",
    "# Step 3: Lossless DPCM Encoding\n",
    "# x̂[n] = x[n-1]\n",
    "# d[n] = x[n] - x̂[n]\n",
    "# First sample x[0] is sent explicitly\n",
    "def lossless_dpcm_encode(sequence):\n",
    "    error = np.zeros_like(sequence, dtype=np.int16)\n",
    "\n",
    "    # First sample: no predictor, transmit as-is\n",
    "    error[0] = sequence[0]\n",
    "\n",
    "    # Remaining samples: difference with previous sample\n",
    "    for i in range(1, len(sequence)):\n",
    "        error[i] = sequence[i] - sequence[i - 1]\n",
    "\n",
    "    return error\n",
    "\n",
    "\n",
    "# Step 4: Lossless DPCM Decoding\n",
    "# x̃[0] = transmitted first sample (error[0])\n",
    "# x̃[n] = x̃[n-1] + d[n]\n",
    "def lossless_dpcm_decode(error):\n",
    "    reconstructed = np.zeros_like(error, dtype=np.int16)\n",
    "\n",
    "    # First sample\n",
    "    reconstructed[0] = error[0]\n",
    "\n",
    "    # Reconstruct rest\n",
    "    for i in range(1, len(error)):\n",
    "        reconstructed[i] = reconstructed[i - 1] + error[i]\n",
    "\n",
    "    return reconstructed\n",
    "\n",
    "\n",
    "# === Testing with image1 ===\n",
    "image = cv2.imread(image1, cv2.IMREAD_GRAYSCALE)\n",
    "sequence = image_to_sequence(image)\n",
    "\n",
    "error = lossless_dpcm_encode(sequence)\n",
    "reconstructed_sequence = lossless_dpcm_decode(error)\n",
    "\n",
    "# Check perfect reconstruction (MSE should be 0)\n",
    "mse = np.mean((sequence - reconstructed_sequence) ** 2)\n",
    "print(\"MSE (lossless DPCM):\", mse)\n",
    "\n",
    "reconstructed_image = sequence_to_image(reconstructed_sequence, image.shape)\n",
    "# Display reconstructed images\n",
    "cv2.imshow(\"Reconstructed Image 1 (Lossless DPCM)\", reconstructed_image)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f70b2103",
   "metadata": {},
   "source": [
    "## Part 2: Lossy DPCM on Image Data (Quantization)\n",
    "\n",
    "Lossy DPCM introduces a **quantizer** after the difference computation to reduce bitrate, at the cost of reconstruction accuracy.\n",
    "\n",
    "### Quantizer Step Size\n",
    "\n",
    "For 8-bit images, the amplitude range of the difference signal is approximately $-128$ to $+128$. The uniform quantizer step size $\\Delta$ is:\n",
    "\n",
    "$$\n",
    "\\Delta = 256 / (2^B)\n",
    "$$\n",
    "\n",
    "> where $B$ is the number of bits used to represent each quantized difference.\n",
    "\n",
    "### Closed-Loop DPCM Encoding\n",
    "\n",
    "Closed-loop encoding uses the reconstructed (quantized) previous value as the predictor:\n",
    "\n",
    "$$\n",
    "\\hat{x}_n = \\tilde{x}_{n-1}\n",
    "$$\n",
    "\n",
    "This ensures that both encoder and decoder use the same prediction reference, which prevents quantization error from accumulating across samples.\n",
    "\n",
    "### Open-Loop DPCM Encoding\n",
    "\n",
    "Open-loop encoding uses the original previous sample for prediction:\n",
    "\n",
    "$$\n",
    "\\hat{x}_n = x_{n-1}\n",
    "$$\n",
    "\n",
    "However, the decoder reconstructs using quantized differences, creating a mismatch:\n",
    "\n",
    "$$\n",
    "\\tilde{x}_n = \\tilde{x}_{n-1} + \\hat{d}_n\n",
    "$$\n",
    "\n",
    "This mismatch causes quantization error to accumulate from sample to sample, resulting in noticeable degradation.\n",
    "\n",
    "### Decoding (Both Modes)\n",
    "\n",
    "Regardless of open- or closed-loop encoding, the decoder reconstructs the signal using:\n",
    "\n",
    "$$\n",
    "\\tilde{x}_n = \\tilde{x}_{n-1} + \\hat{d}_n\n",
    "$$\n",
    "\n",
    "The difference between schemes arises solely from the predictor used during encoding.\n",
    "\n",
    "### Error Metrics: MSE and PSNR\n",
    "\n",
    "Mean Squared Error (MSE) measures the average squared difference between original and reconstructed signals:\n",
    "\n",
    "$$\n",
    "MSE = \\frac{1}{N} \\sum_{n=0}^{N-1} (x_n - \\tilde{x}_n)^2\n",
    "$$\n",
    "\n",
    "**Peak Signal-to-Noise Ratio (PSNR)** measures reconstruction quality relative to signal amplitude:\n",
    "\n",
    "$$\n",
    "PSNR = 10 \\cdot \\log_{10} \\left( \\frac{MAX^2}{MSE} \\right)\n",
    "$$\n",
    "\n",
    "For 8-bit images, $MAX = 255$.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "088dbb9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "\n",
    "# --- 1. Quantizer Function ---\n",
    "def quantize_uniform(value, bits):\n",
    "    \"\"\"\n",
    "    Uniform quantization of the difference signal.\n",
    "    Step size delta = 256 / 2^B.\n",
    "    \"\"\"\n",
    "    if bits >= 8:\n",
    "        return value  # No quantization needed for 8-bit depth\n",
    "\n",
    "    levels = 2**bits\n",
    "    delta = 256 / levels\n",
    "\n",
    "    # Quantize: Divide by delta, round to nearest integer, multiply back\n",
    "    # We add a small epsilon to avoid rounding issues at exact .5 boundaries if needed,\n",
    "    # but standard np.round is sufficient here.\n",
    "    quantized_val = np.round(value / delta) * delta\n",
    "\n",
    "    return quantized_val.astype(np.int16)\n",
    "\n",
    "\n",
    "# --- 2. Metrics Functions ---\n",
    "def compute_metrics(original, reconstructed):\n",
    "    \"\"\"Computes MSE and PSNR.\"\"\"\n",
    "    mse = np.mean((original - reconstructed) ** 2)\n",
    "    if mse == 0:\n",
    "        return 0.0, float(\"inf\")\n",
    "\n",
    "    max_pixel = 255.0\n",
    "    psnr = 10 * np.log10((max_pixel**2) / mse)\n",
    "    return mse, psnr\n",
    "\n",
    "\n",
    "# --- 3. Open-Loop DPCM (Prone to Drift) ---\n",
    "def dpcm_open_loop(sequence, bits):\n",
    "    \"\"\"\n",
    "    Predictor = Original previous sample x[n-1].\n",
    "    Decoder accumulates quantized error, leading to drift.\n",
    "    \"\"\"\n",
    "    n = len(sequence)\n",
    "    reconstructed = np.zeros(n, dtype=np.int16)\n",
    "\n",
    "    # First sample sent explicitly\n",
    "    reconstructed[0] = sequence[0]\n",
    "\n",
    "    for i in range(1, n):\n",
    "        # PREDICTOR: Uses the ORIGINAL previous sample\n",
    "        predictor = sequence[i - 1]\n",
    "\n",
    "        # Difference\n",
    "        diff = sequence[i] - predictor\n",
    "\n",
    "        # Quantize\n",
    "        q_diff = quantize_uniform(diff, bits)\n",
    "\n",
    "        # DECODER: Reconstructs using its own previous reconstruction\n",
    "        # This mismatch (Original Predictor vs Reconstructed History) causes drift\n",
    "        reconstructed[i] = reconstructed[i - 1] + q_diff\n",
    "\n",
    "    return np.clip(reconstructed, 0, 255)\n",
    "\n",
    "\n",
    "# --- 4. Closed-Loop DPCM (Correct Method) ---\n",
    "def dpcm_closed_loop(sequence, bits):\n",
    "    \"\"\"\n",
    "    Predictor = Reconstructed previous sample x_tilde[n-1].\n",
    "    Encoder and Decoder stay in sync.\n",
    "    \"\"\"\n",
    "    n = len(sequence)\n",
    "    reconstructed = np.zeros(n, dtype=np.int16)\n",
    "\n",
    "    # First sample sent explicitly\n",
    "    reconstructed[0] = sequence[0]\n",
    "\n",
    "    for i in range(1, n):\n",
    "        # PREDICTOR: Uses the RECONSTRUCTED previous sample (Feedback Loop)\n",
    "        predictor = reconstructed[i - 1]\n",
    "\n",
    "        # Difference\n",
    "        diff = sequence[i] - predictor\n",
    "\n",
    "        # Quantize\n",
    "        q_diff = quantize_uniform(diff, bits)\n",
    "\n",
    "        # DECODER & ENCODER UPDATE\n",
    "        reconstructed[i] = reconstructed[i - 1] + q_diff\n",
    "\n",
    "    return np.clip(reconstructed, 0, 255)\n",
    "\n",
    "\n",
    "# --- 5. Main Execution ---\n",
    "\n",
    "# Parameters\n",
    "BITS = 3  # Try changing this to 2, 3, or 4 to see the effect!\n",
    "\n",
    "# Run Open Loop\n",
    "rec_open = dpcm_open_loop(sequence, BITS)\n",
    "mse_open, psnr_open = compute_metrics(sequence, rec_open)\n",
    "\n",
    "# Run Closed Loop\n",
    "rec_closed = dpcm_closed_loop(sequence, BITS)\n",
    "mse_closed, psnr_closed = compute_metrics(sequence, rec_closed)\n",
    "\n",
    "# --- Display Results ---\n",
    "print(f\"--- DPCM Results ({BITS} bits) ---\")\n",
    "print(f\"Open Loop   -> MSE: {mse_open:.2f}, PSNR: {psnr_open:.2f} dB\")\n",
    "print(f\"Closed Loop -> MSE: {mse_closed:.2f}, PSNR: {psnr_closed:.2f} dB\")\n",
    "\n",
    "# Reshape for display\n",
    "img_open = sequence_to_image(rec_open, image.shape)\n",
    "img_closed = sequence_to_image(rec_closed, image.shape)\n",
    "\n",
    "cv2.imshow(f\"Open Loop ({BITS} bits) - Drift Visible\", img_open)\n",
    "cv2.imshow(f\"Closed Loop ({BITS} bits) - Corrected\", img_closed)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b870a421",
   "metadata": {},
   "source": [
    "## Part 3: Application to 1D Audio Signal\n",
    "\n",
    "This section applies DPCM concepts to real audio data to visualize error reduction and quantization noise.\n",
    "\n",
    "### Step I — Load and Normalize Audio\n",
    "\n",
    "Load a WAV audio file, extract the samples, and normalize them to a consistent range (e.g., $-1$ to $+1$).\n",
    "\n",
    "## Step II — Lossless DPCM on Audio\n",
    "\n",
    "Apply lossless DPCM encoding. The difference signal will show reduced dynamic range compared to the original waveform.\n",
    "\n",
    "## Step III — Lossy DPCM with Different Bitrates\n",
    "\n",
    "Apply lossy closed-loop DPCM with two bit settings:\n",
    "\n",
    "- High Quality: $B = 4$ bits per difference (16 levels)\n",
    "- High Compression: $B = 2$ bits per difference (4 levels)\n",
    "\n",
    "Lower bit depth introduces more quantization noise, especially in slowly varying regions.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
