{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cc80a493",
   "metadata": {},
   "source": [
    "# TP2- Image Quantization and Dithering\n",
    "\n",
    "## Objective\n",
    "\n",
    "- Understand the effect of color depth reduction (quantization) on an image.\n",
    "- Implement and analyze the visual improvement provided by a common dithering algorithm, specifically Floyd-Steinberg Dithering.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4c7d210",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "imagePath = \"tp2-image.jpg\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb067b56",
   "metadata": {},
   "source": [
    "## Part I - Color Quantization (No Dithering)\n",
    "\n",
    "Goal: Reduce a 24-bit color image (True Color) to a lower bit depth (e.g., 3-bit or 8 unique colors) by simple truncation.\n",
    "\n",
    "1. Load the Image: Load a standard color image (e.g., lena.jpg or a photo with a wide color palette) using cv2.imread().\n",
    "2. Define New Palette: For a 3-bit color space, there are 23=8 possible colors. The colors are (0,0,0), (255,0,0), (0,255,0), (0,0,255), (255,255,0), (0,255,255), (255,0,255), and (255,255,255).\n",
    "3. Quantize: For each pixel in the original image, map its 24-bit color to the nearest color in the 8-color palette. A simpler approach for this part is to divide the 8-bit color channels (0-255) to the nearest of 0 or 255 only (1-bit per channel → 8 colors total).\n",
    "\n",
    "| Channel Value C (0-255) | Quantized Value C′ (0 or 255) |\n",
    "| ----------------------- | ----------------------------- |\n",
    "| C < 128                 | 0                             |\n",
    "| C > 128                 | 255                           |\n",
    "\n",
    "4. Display and Save: Display the original and the highly quantized image side-by-side using cv2.imshow().\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4142bd10",
   "metadata": {},
   "outputs": [],
   "source": [
    "def simpleTruncation(imagePath):\n",
    "    img = cv2.imread(imagePath)\n",
    "    for i in range(img.shape[0]):\n",
    "        for j in range(img.shape[1]):\n",
    "            img[i, j, 0] = 255 if img[i, j, 0] > 127 else 0\n",
    "            img[i, j, 1] = 255 if img[i, j, 1] > 127 else 0\n",
    "            img[i, j, 2] = 255 if img[i, j, 2] > 127 else 0\n",
    "    cv2.imshow(\"Image\", img)\n",
    "    cv2.waitKey(0)\n",
    "    cv2.destroyAllWindows()\n",
    "\n",
    "\n",
    "simpleTruncation(imagePath)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c265b2b",
   "metadata": {},
   "source": [
    "# Part 2: Implementing Floyd-Steinberg Dithering\n",
    "\n",
    "Goal: Apply the Floyd-Steinberg algorithm to distribute the quantization error to neighboring pixels, improving the perceived detail.\n",
    "The Floyd-Steinberg algorithm is an error diffusion method that works by iterating over the pixels, quantizing a pixel, and then adding a weighted fraction of the resulting error to its neighbors that haven't been processed yet:\n",
    "\n",
    "$$\n",
    "\\text{error} = \\text{pixel}_\\text{old} - \\text{pixel}_\\text{new}\n",
    "$$\n",
    "\n",
    "The error is distributed to the four unprocessed neighbors as follows:\n",
    "\n",
    "| Neighbor             | Weight | Fraction |\n",
    "| -------------------- | ------ | -------- |\n",
    "| Right (+1,0)         | 7      | 167      |\n",
    "| Bottom-Left (−1,+1)  | 3      | 163      |\n",
    "| Bottom (0,+1)        | 5      | 165      |\n",
    "| Bottom-Right (+1,+1) | 1      | 161      |\n",
    "\n",
    "### Lab Steps for Part 2:\n",
    "\n",
    "1. Convert and Prepare: Convert the input image to a floating-point type (e.g., np.float32) for accurate error calculations.\n",
    "2. Iterate: Loop through every pixel (row y, column x) of the image.\n",
    "3. Quantize: For the current pixel, calculate the new_pixel value (either 0 or 255 for each channel) using the same quantization rule from Part 1.\n",
    "4. Calculate Error: Calculate the per-channel error between the original pixel value and the new quantized value.\n",
    "5. Diffuse Error: Add the weighted fractions of the error to the appropriate neighbors (ensure you check the image boundaries before adding the error).\n",
    "6. Display and Compare: Display the dithered image and compare it with the images from Part 1.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afe4bc32",
   "metadata": {},
   "outputs": [],
   "source": [
    "def floydSteinberg(imagePath):\n",
    "    # Read the image\n",
    "    img = cv2.imread(imagePath)\n",
    "    # Transform to float\n",
    "    floatImage = np.array(img, np.float32)\n",
    "    # Loop through each pixel\n",
    "    for i in range(floatImage.shape[0]):\n",
    "        for j in range(floatImage.shape[1]):\n",
    "            # get current values\n",
    "            r = floatImage[i, j, 0]\n",
    "            g = floatImage[i, j, 1]\n",
    "            b = floatImage[i, j, 2]\n",
    "            # Quantize\n",
    "            floatImage[i, j, 0] = 255 if floatImage[i, j, 0] > 127 else 0\n",
    "            floatImage[i, j, 1] = 255 if floatImage[i, j, 1] > 127 else 0\n",
    "            floatImage[i, j, 2] = 255 if floatImage[i, j, 2] > 127 else 0\n",
    "            # Calculate error\n",
    "            error_r = r - floatImage[i, j, 0]\n",
    "            error_g = g - floatImage[i, j, 1]\n",
    "            error_b = b - floatImage[i, j, 2]\n",
    "            # Add the weighted error to the neighbors\n",
    "            if j + 1 < floatImage.shape[1]:\n",
    "                floatImage[i, j + 1, 0] += error_r * (7 / 167)\n",
    "                floatImage[i, j + 1, 1] += error_g * (7 / 167)\n",
    "                floatImage[i, j + 1, 2] += error_b * (7 / 167)\n",
    "\n",
    "            if i + 1 < floatImage.shape[0] and j - 1 >= 0:\n",
    "                floatImage[i + 1, j - 1, 0] += error_r * (3 / 163)\n",
    "                floatImage[i + 1, j - 1, 1] += error_g * (3 / 163)\n",
    "                floatImage[i + 1, j - 1, 2] += error_b * (3 / 163)\n",
    "\n",
    "            if i + 1 < floatImage.shape[0]:\n",
    "                floatImage[i + 1, j, 0] += error_r * (5 / 165)\n",
    "                floatImage[i + 1, j, 1] += error_g * (5 / 165)\n",
    "                floatImage[i + 1, j, 2] += error_b * (5 / 165)\n",
    "\n",
    "            if i + 1 < floatImage.shape[0] and j + 1 < floatImage.shape[1]:\n",
    "                floatImage[i + 1, j + 1, 0] += error_r * (1 / 161)\n",
    "                floatImage[i + 1, j + 1, 1] += error_g * (1 / 161)\n",
    "                floatImage[i + 1, j + 1, 2] += error_b * (1 / 161)\n",
    "\n",
    "    cv2.imshow(\"New Dithered Image\", floatImage)\n",
    "    cv2.waitKey(0)\n",
    "    cv2.destroyAllWindows()\n",
    "\n",
    "\n",
    "floydSteinberg(imagePath)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.13.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
