实现OpenCV compareHist:离散直方图输入格式咨询
Hey there! Let's break down exactly how to prep your discrete histograms for OpenCV's compareHist function—this is a super common gotcha with the function's input requirements.
compareHist First, let's cut to the chase: compareHist doesn't care about your bin labels directly. It only needs flat, ordered arrays of frequency values from both histograms, aligned perfectly by their bin indices.
Required Input Structure
Both histograms need to be:
- 1-dimensional arrays (either NumPy arrays or OpenCV
Matobjects) - Composed solely of the
freqvalues from your table - Ordered to match their corresponding bin indices (e.g., bin 0's freq first, then bin 1's, bin 2's, etc.—which your existing data already follows)
- Stored as
float32data type (OpenCV's preferred format for histogram operations)
Step-by-Step Conversion Example
Suppose your first histogram looks like this:
bins freq
0 1000
1 200
2 100
3 400
You'd convert it to a valid input array like this (using NumPy, which plays seamlessly with OpenCV):
import numpy as np hist1 = np.array([1000, 200, 100, 400], dtype=np.float32)
Repeat this exact process for your second histogram—critical note: both arrays must have the same length (same number of bins). If one histogram has bins the other doesn't, fill those missing bins with a frequency of 0 to align them.
Quick Usage Example
Once your histograms are formatted correctly, using compareHist is simple. Here's a quick snippet:
import cv2 # Assume hist1 and hist2 are your properly formatted arrays # Choose a comparison method that fits your use case similarity_score = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL) print(f"Histogram similarity: {similarity_score}")
Popular comparison methods include HISTCMP_CHISQR (chi-square distance), HISTCMP_BHATTACHARYYA (Bhattacharyya distance), and HISTCMP_INTERSECT (intersection method).
内容的提问来源于stack exchange,提问作者kncdwn

