1、应用场景
找出图片中某目标,该目标最好具有直方图特征。
需要输入待找出物体的图片模板:img1,待识别图片:img2。
2、原理过程
a)计算直方图:先将图像转为hsv,制作h与s两个通道的二维直方图。
b)计算比率:用待找出物体的图片模板直方图/待识别图片直方图。
c)卷积模糊
b)反向输出
如下找到图片中的手掌区域的应用:
2、相关API
计算直方图
void cv::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
)
images——这里是指针,所以输入图像时,必须采用输入地址的形式, 如:&image。
nimages ——计算直方图的图片数量
channels ——待计算直方图的维度索引列表。
mask——掩膜图像
hist——输出图像
dims——维度数量
histSize ——每一个维度的图像被分成的块的数量
ranges ——每个维度的像素值范围
uniform——bool型,是否均匀分布。
accumulate ——Accumulation flag. If it is set, the histogram is not cleared in the beginning when it is allocated. This feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time.
void cv::calcBackProject ( const Mat * images,
int nimages,
const int * channels,
InputArray hist,
OutputArray backProject,
const float ** ranges,
double scale = 1,
bool uniform = true
)
hist——模板直方图图像
backProject ——输出
scale——Optional scale factor for the output back projection.
3、代码
void QuickDemo::back_infection(Mat& part, Mat& full)
{
//计算直方图
Mat model_hsv, image_hsv;
cvtColor(part, model_hsv, COLOR_BGR2HSV);
cvtColor(full, image_hsv, COLOR_BGR2HSV);
int h_bins = 48, s_bins = 48;
int hist_size[] = { h_bins, s_bins };
int channels[] = { 0,1 };
Mat roiHist;
float h_ranges[] = {0,180};
float s_ranges[] = { 0,255 };
const float* ranges[] = { h_ranges,s_ranges };
calcHist(&model_hsv, 1, channels, Mat(), // do not use mask
roiHist, 2, hist_size, ranges,
true, // the histogram is uniform
false);
normalize(roiHist, roiHist, 0, 255, NORM_MINMAX, -1, Mat());//归一化到0~255
MatND backporj;
calcBackProject(&image_hsv,1, channels, roiHist, backporj, ranges, 1);
namedWindow("result", WINDOW_FREERATIO);
imshow("result", backporj);
}