Opencv-图像直方图反向投影

图像直方图反向投影

    • 知识点
    • python代码
    • c++代码

知识点

图像直方图反向投影
文字解释:
图像直方图反向投影是通过构建指定模板图像的二维直方图空间与目标的二维直方图空间,进行直方图数据归一化之后, 进行比率操作,对所有得到非零数值,生成查找表对原图像进行像素映射之后,再进行图像模糊输出的结果。
直方图反向投影流程:

  • 计算直方图
  • 计算比率R
  • LUT查找表
  • 卷积模糊
  • 归一化输出

相关API

  • calcBackProject
    Opencv-图像直方图反向投影_第1张图片

python代码

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt


def back_projection_demo():
    sample = cv.imread("C:/Users/qqxd/Desktop/opencvcode/images/sample.png")
    # hist2d_demo(sample)
    target = cv.imread("C:/Users/qqxd/Desktop/opencvcode/images/target.png")
    # hist2d_demo(target)
    roi_hsv = cv.cvtColor(sample, cv.COLOR_BGR2HSV)
    target_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)

    # show images
    cv.imshow("sample", sample)
    cv.imshow("target", target)

    roiHist = cv.calcHist([roi_hsv], [0, 1], None, [32, 32], [0, 180, 0, 256])
    cv.normalize(roiHist, roiHist, 0, 255, cv.NORM_MINMAX)
    dst = cv.calcBackProject([target_hsv], [0, 1], roiHist, [0, 180, 0, 256], 1)
    cv.imshow("backProjectionDemo", dst)


def hist2d_demo(image):
    hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
    hist = cv.calcHist([hsv], [0, 1], None, [32, 32], [0, 180, 0, 256])
    dst = cv.resize(hist, (400, 400))
    cv.imshow("image", image)
    cv.imshow("hist", dst)
    plt.imshow(hist, interpolation='nearest')
    plt.title("2D Histogram")
    plt.show()

src = cv.imread("C:/Users/qqxd/Desktop/opencvcode/images/target.png")
back_projection_demo()
hist2d_demo(src)
cv.waitKey(0)

cv.destroyAllWindows()

c++代码

#include 
#include 

using namespace cv;
using namespace std;

const int bins = 256;
Mat src;
const char* winTitle = "input image";
void backProjection_demo(Mat &image, Mat &model);
int main(int argc, char** argv) {
	Mat src = imread("C:/Users/qqxd/Desktop/opencvcode/images/sample.png");
	Mat model = imread("C:/Users/qqxd/Desktop/opencvcode/images/target.png");
	if (src.empty() || model.empty()) {
		printf("could not load image...\n");
		return 0;
	}
	namedWindow(winTitle, WINDOW_AUTOSIZE);
	imshow(winTitle, src);
	imshow("model", model);

	backProjection_demo(src, model);
	waitKey(0);
	return 0;
}

void backProjection_demo(Mat &image, Mat &model) {
	Mat model_hsv, image_hsv;
	cvtColor(model, model_hsv, COLOR_BGR2HSV);
	cvtColor(image, image_hsv, COLOR_BGR2HSV);

	// 定义直方图参数与属性
	int h_bins = 32; int s_bins = 32;
	int histSize[] = { h_bins, s_bins };
	// hue varies from 0 to 179, saturation from 0 to 255
	float h_ranges[] = { 0, 180 };
	float s_ranges[] = { 0, 256 };
	const float* ranges[] = { h_ranges, s_ranges };
	int channels[] = { 0, 1 };
	Mat roiHist;
	calcHist(&model_hsv, 1, channels, Mat(), roiHist, 2, histSize, ranges, true, false);
	normalize(roiHist, roiHist, 0, 255, NORM_MINMAX, -1, Mat());
	MatND backproj;
	calcBackProject(&image_hsv, 1, channels, roiHist, backproj, ranges, 1.0);
	imshow("BackProj", backproj);
}

运行结果如下:
Opencv-图像直方图反向投影_第2张图片
Opencv-图像直方图反向投影_第3张图片

你可能感兴趣的:(Opencv)