You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现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.

How to Format Histograms for OpenCV's 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 Mat objects)
  • Composed solely of the freq values 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 float32 data 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:18:10