快乐虾
http://blog.csdn.net/lights_joy/
欢迎转载,但请保留作者信息
直方图的计算采用OpenCV的calcHist完成。
OpenCV的C++接口中calcHist有三种形式:
//! computes the joint dense histogram for a set of images. CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false ); //! computes the joint sparse histogram for a set of images. CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, SparseMat& hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false ); CV_EXPORTS_W void calcHist( InputArrayOfArrays images, const vector<int>& channels, InputArray mask, OutputArray hist, const vector<int>& histSize, const vector<float>& ranges, bool accumulate=false );
但导出的Python接口却只有一个:
static PyObject* pyopencv_calcHist(PyObject* , PyObject* args, PyObject* kw) { PyObject* pyobj_images = NULL; vector_Mat images; PyObject* pyobj_channels = NULL; vector_int channels; PyObject* pyobj_mask = NULL; Mat mask; PyObject* pyobj_hist = NULL; Mat hist; PyObject* pyobj_histSize = NULL; vector_int histSize; PyObject* pyobj_ranges = NULL; vector_float ranges; bool accumulate=false; const char* keywords[] = { "images", "channels", "mask", "histSize", "ranges", "hist", "accumulate", NULL }; if( PyArg_ParseTupleAndKeywords(args, kw, "OOOOO|Ob:calcHist", (char**)keywords, &pyobj_images, &pyobj_channels, &pyobj_mask, &pyobj_histSize, &pyobj_ranges, &pyobj_hist, &accumulate) && pyopencv_to(pyobj_images, images, ArgInfo("images", 0)) && pyopencv_to(pyobj_channels, channels, ArgInfo("channels", 0)) && pyopencv_to(pyobj_mask, mask, ArgInfo("mask", 0)) && pyopencv_to(pyobj_hist, hist, ArgInfo("hist", 1)) && pyopencv_to(pyobj_histSize, histSize, ArgInfo("histSize", 0)) && pyopencv_to(pyobj_ranges, ranges, ArgInfo("ranges", 0)) ) { ERRWRAP2( cv::calcHist(images, channels, mask, hist, histSize, ranges, accumulate)); return pyopencv_from(hist); } return NULL; }
因此Python的接口看起来有点奇怪:
hist = cv2.calcHist([src], [0], None, [256], [0, 255])
即使是只对一张图片进行操作,也必须使用数组的形式进行参数传递。
写个简单的Python程序,获取单个通道的直方图:
# -*- coding: utf-8 -*- import cv2 import numpy as np import matplotlib.pyplot as plt # 单通道直方图测试 src = cv2.imread('f:\\tmp\\cotton.jpg') cv2.imshow('src', src) hist = cv2.calcHist([src], [0], None, [256], [0, 255]) plt.plot(hist) plt.show() cv2.waitKey()
结果如下:
符合我们对直方图的预期。