v9.1.1
Menu

Color Histogram Comparison

mediumPROColor SpacesComputer Vision 2

Implement a function to compare two color histograms by calculating the chi-squared distance between them. This task involves understanding how to quantify the similarity between two distributions, which is crucial in computer vision for image analysis and object recognition.

The chi-squared distance is a measure used to compare the distribution of two histograms, which in this case represent the color distributions of two images. It is based on the idea of calculating the difference between the expected and observed frequencies in each bin of the histograms. The formula for the chi-squared distance is derived from the chi-squared statistic, which is commonly used in statistical tests to determine how well observed data fit expected distributions.

Each bin contributes the squared difference of its two counts divided by the bin's combined count. A bin where both counts are zero contributes nothing (its term would be 0/00/0) and is skipped. The distance is the total over all bins, returned as a float rounded to 4 decimal places.

χ2=∑i(h1[i]−h2[i])2h1[i]+h2[i]\chi^2 = \sum_{i} \frac{(h_1[i] - h_2[i])^2}{h_1[i] + h_2[i]}

This technique is widely used in image retrieval and object recognition systems to compare the color content of images.

Example

Input
h1 = [1, 2, 3, 4], h2 = [1, 2, 3, 4]
Output
0.0
Reasoning
  • Inputs: h1=[1,2,3,4]h_1 = [1, 2, 3, 4] and h2=[1,2,3,4]h_2 = [1, 2, 3, 4] are two 4-bin colour histograms. Entry ii is the number of pixels whose colour fell into bin ii.
  • Bin totals: h1,i+h2,ih_{1,i} + h_{2,i} gives 2,4,6,82, 4, 6, 8. All are positive, so no bin is skipped and every denominator is safe.
  • Bin differences: h1,i−h2,i=0h_{1,i} - h_{2,i} = 0 in every bin, so each squared numerator is 00.
  • Sum: χ2=02+04+06+08=0\chi^2 = \frac{0}{2} + \frac{0}{4} + \frac{0}{6} + \frac{0}{8} = 0, which at 4 decimal places is the float 0.0.
  • Notice: the distance is 00 exactly when the histograms match bin for bin, and it grows as counts shift between bins. For [5,5,5][5, 5, 5] against [3,5,7][3, 5, 7] it is 48+0+412≈0.8333\frac{4}{8} + 0 + \frac{4}{12} \approx 0.8333. Dividing by the bin total means a gap of 2 counts weighs more in a sparse bin than in a crowded one.

Constraints

  • h1 and h2 are lists of non-negative numbers with equal length
  • Skip bins where both counts are 0
  • Return a single float rounded to 4 decimal places

More from Computer Vision 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.