Chapter 4: Color Models (CSS 433 Computer Vision)

1. Color Filter Array (CFA) & Demosaicing

1.1 The Physical Problem

Digital image sensors (CCD and CMOS) are inherently monochromatic (panchromatic): each photodiode simply accumulates incoming photons and generates a charge proportional to total radiant energy, without differentiating between wavelengths.

To produce a color image without using three separate physical sensor chips and an optical beam-splitter, a Color Filter Array (CFA) is placed directly over the pixel lattice. The most ubiquitous CFA is the Bayer Filter Pattern, which uses a repeating mosaic:

  • 50% Green, 25% Red, 25% Blue: Green pixels are twice as dense because the Human Visual System’s (HVS) photopic luminous efficiency peaks near (green band). The human eye relies primarily on green wavelengths to resolve fine spatial detail and luminance.
  • Demosaicing (CFA Interpolation): The computational process of reconstructing the two missing color channels at every pixel position from the surrounding mosaic samples to yield a full 3-channel RGB image.
  • RAW vs. Firmware Interpolation: A digital camera’s RAW format records the unprocessed sensor readings straight from the CFA. Saving in RAW allows offline, higher-order demosaicing algorithms on a computer rather than relying on the camera’s real-time hardware ASIC.

1.2 Mathematical Foundations: 1-D Linear Interpolation

Linear interpolation estimates an intermediate value between two known points and via an inverse-distance weighted average.

       v1 o
          | \
          |   \
          |     \  vx
          |       o-------
          |       |      |
          |       |      o v2
          |       |      |
      ----+-------+------+----
          |<--m-->|<--n->|
             x1       x      x2

Let the distance between and be , and between and be . The total interval is :

Notice the inverse proportionality: The closer is to (smaller ), the larger the weight assigned to (weight is proportional to ).

Numerical Example:

Let at , and at . Find at .

  • .

1.3 Detailed Solution to Exercise 1: 2-D CFA Interpolation

Problem Statement:

In a Bayer array, a “virtual pixel” is located inside a cell bounded by the surrounding physical CCD cells. By extending 1-D linear interpolation into 2-D (bilinear interpolation), derive the formulas for:

                Column Grid (spacing d = 1)
              Col 1    Col 2    Col 3    Col 4
    Row 1:   [ R1  ]  [ G2  ]  [ R3  ]  [ G4  ]
    Row 2:   [ G5  ]  [ B6  ]  [ G7  ]  [ B8  ]
                        \        |
                         \   (Px)| (at row 2.5, col 2.5)
                          \      |
    Row 3:   [ R9  ]  [ G10 ]  [ R11 ]  [ G12 ]
    Row 4:   [ G13 ]  [ B14 ]  [ G15 ]  [ B16 ]

Step-by-Step Derivations:

1. Green Channel ():

  • Looking at the mosaic around , the two closest green sensors are (at Row 2, Col 3) and (at Row 3, Col 2).
  • The virtual pixel is located at the center intersection (Row 2.5, Col 2.5).
  • The Euclidean distance from to is:
  • The Euclidean distance from to is:
  • Since , the weights are equal ():

2. Red Channel ():

The four surrounding red sensors are located at:

  • : Row 1, Col 1
  • : Row 1, Col 3
  • : Row 3, Col 1
  • : Row 3, Col 3

The virtual pixel is located at . Notice that samples form a grid with spacing units between adjacent red sensors:

  • In the vertical direction: Row 1 is at , Row 3 is at . The point divides the interval into:

    • Distance from Row 1:
    • Distance from Row 3:
    • Normalized weights along :
  • In the horizontal direction: Col 1 is at , Col 3 is at . The point divides the interval into:

    • Distance from Col 1:
    • Distance from Col 3:
    • Normalized weights along :

By 2-D separable bilinear interpolation, the weight for any corner is the product of its 1-D directional weights ():

  • Weight for (Row 3, Col 3):
  • Weight for (Row 1, Col 3):
  • Weight for (Row 3, Col 1):
  • Weight for (Row 1, Col 1):

Summing these contributions yields the exact formula from the slide:


3. Blue Channel ():

The surrounding blue sensors are located at:

  • : Row 2, Col 2
  • : Row 2, Col 4
  • : Row 4, Col 2
  • : Row 4, Col 4

The virtual pixel is at .

  • Along the vertical direction between Row 2 and Row 4:
    • Distance to Row 2:
    • Distance to Row 4:
  • Along the horizontal direction between Col 2 and Col 4:
    • Distance to Col 2:
    • Distance to Col 4:

Computing the product weights:

  • Weight for (Row 2, Col 2):
  • Weight for (Row 2, Col 4):
  • Weight for (Row 4, Col 2):
  • Weight for (Row 4, Col 4):

Thus:


1.4 Detailed Solution to Exercise 2: Adaptive/Gradient-Based CFA Interpolation

Problem Statement:

To interpolate the missing green value at blue position :

(where is a small scalar threshold).
Explain the benefit of this approach compared to primitive averaging.

                     G12 (above)
                      |
        G21 (left) -- B22 -- G23 (right)
                      |
                     G32 (below)

Detailed Explanation & Benefits:

  1. Gradient Measures Spatial Discontinuity:
    • computes the absolute rate of change in the vertical direction. A high value of indicates a sharp transition or edge running horizontally between Row 1 and Row 3.
    • computes the rate of change in the horizontal direction. A high value of indicates an edge running vertically between Col 1 and Col 3.
  2. Edge-Directed Smoothing (Interpolate ALONG edges, never ACROSS them):
    • Case 1 (): The vertical gradient is significantly larger than the horizontal gradient. This means a sharp horizontal edge exists across the vertical axis. Averaging vertically ( and ) would blend two completely different color regions, causing blurring and false colors. Therefore, the algorithm interpolates horizontally along the edge where variation is low: .
    • Case 2 (): A sharp vertical edge exists. The algorithm interpolates vertically along the edge: .
    • Case 3 (): The region is flat (or equally smooth in both directions), so it safely performs a 4-neighbor isotropic average: .
  3. Elimination of “Zipper Artifacts”: Primitive non-adaptive averaging blurs color channels across high-contrast edges. Because different channels sample different spatial points, this cross-edge blur creates alternating false color fringes resembling a zipper along boundaries. Edge-adaptive interpolation prevents this by respecting image gradients.

2. RGB Color Model & Distance Metrics

2.1 RGB Cube Fundamentals

  • Additive Model: Colors are generated by emitting light. Combining full red, green, and blue intensities yields white: .
  • Subtractive (CMY/YMC) Model: Used for printing and inks. Dyes absorb (subtract) specific wavelengths from incident white light:
  • Achromatic Diagonal (Grayscale Line): Connects the origin (black) to (white), where .

2.2 Luminance Conversion: rgb2gray

When converting an RGB image to grayscale, human perception does not weigh the three primary colors equally. MATLAB’s rgb2gray implements the standard NTSC/YIQ luminance equation:

  • Green contributes of perceived luminance.
  • Red contributes .
  • Blue contributes only .

2.3 Detailed Solution to Exercise 3: Distance Metrics in RGB Space

Given two color vectors in RGB space: Define the difference vector as:

                           B
                           ^
                           |    C2 (r2, g2, b2)
                           |   /
                           |  /  Euclidean Distance (L2)
                           | /
                           |/____ C1 (r1, g1, b1)
                           +-------------------> G
                          /
                         /
                        v R

1. SAD (Sum of Absolute Differences) / Norm / Manhattan Distance:

Measures the sum of rectilinear steps across each axis:

2. SSD (Sum of Squared Differences):

Accumulates squared errors:

3. ED (Euclidean Distance) / Norm:

The straight-line geometric distance in 3D Euclidean space:

4. MAD (Maximum of Absolute Differences) / Norm / Chebyshev Distance:

Determined solely by the single color channel with the worst mismatch:


Comprehensive Numerical Example:

Let Color 1 be an orange tone:
Let Color 2 be an olive tone:

  1. Component Differences:
  2. SAD ():
  3. SSD:
  4. ED ():
  5. MAD ():

3. The HSV (HSI) Color Model

3.1 Intuition & Perceptual Motivation

  • Hue (): Represents dominant wavelength (the actual color attribute, such as “red”, “cyan”, “purple”). It is an angular measure on a circular wheel: (or normalized ).
  • Saturation (): The purity of the color, or how much white light is mixed in. is a pure spectral color; is a shade of gray.
  • Intensity () / Value (): The brightness / light energy.
    • (average intensity, forming a double hexcone).
    • (peak brightness, forming a single hexcone).

3.2 RGB to HSI Mathematical Formulation

For :


3.3 Detailed Solution to Exercise 4: Hue and Saturation

Part 1: Derive Hue Angles for the Primary and Secondary Colors

Let us evaluate each color vector through the mathematical formula:

1. Pure Red:
  • Numerator:
  • Denominator:
  • Since (), .
2. Pure Yellow:
  • Numerator:
  • Denominator:
  • Since (), .
3. Pure Green:
  • Numerator:
  • Denominator:
  • Since (), .
4. Pure Cyan:
  • Numerator:
  • Denominator:
  • Since (), .
5. Pure Blue:
  • Numerator:
  • Denominator:
  • Crucial step: Here (). Therefore:
6. Pure Magenta:
  • Numerator:
  • Denominator:
  • Here (). Therefore:

Summary Table of Standard Hue Angles:

Color NameCalculated Hue ConditionFinal Hue MATLAB ()
Red
Yellow
Green
Cyan
Blue
Magenta

Part 2: Find the Saturation along the Diagonal Line from to

  • Along the main diagonal connecting black to white, every point has equal color components:
  • Substitute into the saturation formula:
  • Conclusion: Saturation is identically along the entire diagonal. This confirms that the diagonal represents the purely achromatic grayscale axis.

Part 3: Find the Saturation along the 12 Edges of the RGB Color Cube

The RGB cube has 12 distinct edges:

  1. 3 Edges emanating from Black :
    • From to (along Red axis): Here .
    • From to (along Green axis): .
    • From to (along Blue axis): .
  2. 6 Outer Boundary Edges connecting Primaries to Secondaries:
    • (Red to Yellow): , so .
    • (Green to Yellow): .
    • (Green to Cyan): .
    • (Blue to Cyan): .
    • (Blue to Magenta): .
    • (Red to Magenta): .
    • Across all these 6 edges, at least one component remains 0, so everywhere.
  3. 3 Edges converging to White :
    • From Yellow to White : Here , while varies from .
      • At Yellow (): .
      • At White (): .
      • Saturation drops monotonically from down to .
    • From Cyan to White : , while varies from .
    • From Magenta to White : , while varies from .

3.4 Detailed Solution to Exercise 5: Negative Color (Thai National Flag)

Problem Statement:

The Thai flag consists of three stripe colors:

  • Red:
  • White:
  • Blue:
   Thai Flag Stripes:
   -----------------------------------  RED
   -----------------------------------  WHITE
   ===================================  BLUE (Double width)
   -----------------------------------  WHITE
   -----------------------------------  RED

Question 1: What happens if ONLY the Hue of the flag is inverted?

  • Inverting hue means shifting the hue angle by (the diametrically opposite complementary color):
  • Red Stripe:
    • Original: .
    • Inverted Hue: .
    • corresponds to Cyan.
    • With and original , the RGB values become (a dark cyan).
  • Blue Stripe:
    • Original: .
    • Inverted Hue: .
    • corresponds to Yellow.
    • With and original , the RGB values become (a dark yellow/olive).
  • White Stripe:
    • Original: .
    • Because , Hue is undefined (a mathematical singularity).
    • Inverting an undefined angle leaves the saturation at and intensity at .
    • The white stripe remains completely unchanged (White)!
  • Resulting Flag: Cyan stripes on the outside, unchanged White middle borders, and a Yellow central stripe.

Question 2: How does the true negative of the flag image look?

The true photographic negative is defined in linear RGB space by taking the complement of every channel:

  • Red :
  • White :
  • Blue :

Resulting Negative Flag: Bright Cyan outer stripes, Black middle stripes, and a bright Yellow center stripe.


Question 3: What does the sum of the flag and its negative look like?

For every pixel in the entire image:

  • Red: (White)
  • White: (White)
  • Blue: (White)

Result: A completely uniform, flat Pure White image everywhere.


3.5 Detailed Solution to Exercise 6: Evaluating Hue Differences

Problem Statement:

Hue values are normalized such that maps to . We wish to evaluate the difference between two hue values and .
Discuss whether it is appropriate to use .

                     0.0 (Red: 0 deg)
                     /      \
            (330 deg)        (30 deg)
            B = 0.917        A = 0.083
                     \      /
                    0.5 (Cyan: 180 deg)

Detailed Mathematical Analysis:

  • Why Fails: Hue is an angular (circular) coordinate, not a linear Cartesian metric. The points () and () are visually near-identical shades of pure red separated by only . However, the naive absolute difference calculates: This formula incorrectly treats them as being nearly across the entire color space.

  • The Correct Metric (Circular Shortest Angular Distance): The true distance between two angles on a circle is the shortest path along the circumference:

    Testing on () and ():

    • (which equals )
    • (the true separation!).

4. Practical CV Applications of Color Processing

                       RGB Input Image
                             |
                   Convert to HSV [rgb2hsv]
                             |
             +---------------+---------------+
             |                               |
        Hue & Saturation                  Intensity
             |                               |
    Color Segmentation / Tracking      Spatial Filtering / Equalization
    - Skin detection (Bradski)        - Smoothing (Box/Gaussian)
    - CAMSHIFT object tracking        - Sharpening (Laplacian)
    - Avoid low S/I singularities     - Histogram Equalization
             |                               |
             +---------------+---------------+
                             |
                   Convert back to RGB [hsv2rgb]
                     (NO Color Fringing!)

4.1 Histogram Equalization in HSV Space (Slide 26)

  • Pitfall of RGB Equalization: Applying histogram equalization to each channel () independently alters their relative ratios at every pixel: This severely corrupts the original color tones, shifting hues and introducing heavy color distortion.
  • The HSV Solution:
    1. Convert RGB HSV.
    2. Leave Hue () completely untouched.
    3. Apply histogram equalization only to the Value () or Intensity () channel.
    4. Optionally apply a modest contrast stretch to Saturation () to prevent washed-out appearances.
    5. Convert HSV back to RGB. Result: Contrast is enhanced while natural color balance and chromaticity remain intact.

4.2 Spatial Smoothing and Sharpening in HSV (Slides 27–28)

  • Problem: Convolving a averaging mask or a Laplacian sharpening mask across independently causes edge-color bleeding. Because primary channels have different edge transitions, sharpening independently causes rainbow-colored rings along edges.
  • Solution: Filter only the Intensity () plane: Then recombine with unchanged and channels. The edges appear crisp without chromatic fringing.

4.3 Skin-Color Detection & CAMSHIFT Tracking (Slides 29–32)

  • Bradski’s Finding (1998): Except for albinos, human skin across different ethnicities shares a surprisingly narrow, consistent Hue range (predominantly in the orange/red-yellow spectral band). Ethnic differences arise primarily from variations in melanin concentration, which alters Intensity () and Saturation (), while the underlying chromatic Hue remains virtually invariant.
  • Hue-Based Segmentation Rule: A pixel belongs to skin if:
  • Singularities / Failure Modes of Hue: Hue becomes unstable or undefined under two conditions:
    1. Low Saturation (): In near-gray, white, or black areas, the RGB vector sits close to the central diagonal. Minor sensor noise flips the angular calculation drastically.
    2. Extremely Low/High Intensity ( or ): At the tips of the color hexcone/bicone, the cross-sectional area shrinks to a point, making Hue calculation ill-conditioned.
  • CAMSHIFT (Continuously Adaptive Mean Shift):
    1. Computes a 1-D Hue histogram of the target object.
    2. Computes the Color Back-Projection image, where each pixel value is its probability of belonging to the object given its Hue:
    3. Uses Mean Shift to find the mode (center of mass) of the probability distribution.
    4. Dynamically resizes and rotates the tracking search window according to the 0th, 1st, and 2nd spatial moments:

5. Digital Image File Formats & Safe RGB Colors

5.1 Comparison of Image File Formats (Slides 34–35)

FormatExtensionCompression TypeAlgorithmMax Bit DepthPrimary Engineering Usage
BMP.bmpUncompressed (optional RLE)None / Run-Length24-bit TrueColorWindows OS native, raw uncompressed storage.
TIFF.tif, .tiffLosslessLZW, Deflate24-bit / 48-bit / FloatMedical imaging, scientific cameras, prepress printing.
PNG.pngLossless2D prediction + DEFLATE (LZ77 + Huffman)24-bit + 8-bit AlphaWeb graphics, transparent overlays, diagrams.
JPEG.jpg, .jpegLossy Block DCT + Quantization + Huffman24-bit TrueColorNatural photographic images (poor for line art/text).
GIF.gifLossless (palette-quantized)LZW8-bit Indexed (max 256 colors)Short animations, simple web banners, low-color icons.

File Size Relationship for the same lossless image:


5.2 Safe RGB Colors & The Web-Safe Palette (Slides 36–38)

In early computer graphics hardware, display frame buffers were limited to 8 bits per pixel ( colors). To prevent operating systems from dithering arbitrarily, a standardized subset called the Web-Safe Palette was established.

  • Each primary channel () is allowed only 6 evenly spaced discrete intensity levels:

  • Total Safe Colors:
  • The remaining color indices in an 8-bit table were reserved by the operating system (Windows/Mac system UI colors).

Quantitative Ratio Problem (Slide 37):

Find the ratio between the number of safe colors and the total number of colors in a 24-bit RGB true-color space.

  1. Total 24-bit colors:
  2. Total safe colors:
  3. Ratio calculation: Exam Insight: The web-safe palette represents just over one-thousandth of one percent of the full 24-bit color spectrum.

5.3 Indexed RGB Images (Slides 39–41)

Instead of storing three bytes () for every pixel (which requires bytes), an Indexed Image uses two separate data structures:

    IMAGE ARRAY (Size: M x N)                 COLOR MAP MATRIX (Size: 256 x 3)
      Indices: uint8 (0 to 255)                     Values: double [0.0, 1.0]
    +-----+-----+-----+-----+                      Index      R       G       B
    |  0  |  5  |  5  | 12  |                      +-----+--------+-------+-------+
    +-----+-----+-----+-----+                      |  0  | 0.0000 | 0.000 | 0.000 |
    |  5  | 18  | 31  | 12  | ---- Index 5 ------> | ... |  ...   |  ...  |  ...  |
    +-----+-----+-----+-----+                      |  5  | 0.2902 | 0.063 | 0.063 |
    |  2  | 31  | 31  | 18  |                      | ... |  ...   |  ...  |  ...  |
    +-----+-----+-----+-----+                      | 255 | 1.0000 | 1.000 | 1.000 |
                                                   +-----+--------+-------+-------+
  1. Image Array (img2): An matrix of integers (uint8), where each entry is a pointer/index into the colormap.
  2. Color Map Matrix (map): A lookup table (typically ) containing the normalized floating-point RGB components (double from to ) for each index.

Memory Comparison Example (from Slide 40):

For an image of size :

  • TrueColor RGB (img1):
  • Indexed Representation (img2 + map):
    • Image Array:
    • Colormap:
    • Total:
  • Storage Savings: Reduces required memory to of the original uncompressed RGB image.