본문 바로가기

OpenCV

ch10 backproj

# python

import cv2
import numpy as np

# Calculate CrCb histogram from a reference image
ref = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch10\\backproj\\ref.png", cv2.IMREAD_COLOR)
mask = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch10\\backproj\\mask.bmp", cv2.IMREAD_GRAYSCALE)
ref_ycrcb = cv2.cvtColor(ref, cv2.COLOR_BGR2YCrCb)

channels = [1, 2]
cr_bins = 128
cb_bins = 128
histSize = [cr_bins, cb_bins]
cr_range = [0, 256]
cb_range = [0, 256]
ranges =[0, 256, 0, 256] # [cr_range, cb_range]

hist = cv2.calcHist([ref_ycrcb], channels, mask, histSize, ranges)

# Apply histogram backprojection to an input image
src = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch10\\backproj\\kids.png", cv2.IMREAD_COLOR)
src_ycrcb = cv2.cvtColor(src, cv2.COLOR_BGR2YCrCb)

backproj = cv2.calcBackProject([src_ycrcb], channels, hist, ranges, 1)

cv2.imshow("src", src)
cv2.imshow("backproj", backproj)
cv2.waitKey(0)
cv2.destroyAllWindows()

// C++

#include "opencv2/opencv.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
	// Calculate CrCb histogram from a reference image

	Mat ref, ref_ycrcb, mask;
	ref = imread("ref.png", IMREAD_COLOR);
	mask = imread("mask.bmp", IMREAD_GRAYSCALE);
	cvtColor(ref, ref_ycrcb, COLOR_BGR2YCrCb);

	Mat hist;
	int channels[] = { 1, 2 };
	int cr_bins = 128; int cb_bins = 128;
	int histSize[] = { cr_bins, cb_bins };
	float cr_range[] = { 0, 256 };
	float cb_range[] = { 0, 256 };
	const float* ranges[] = { cr_range, cb_range };

	calcHist(&ref_ycrcb, 1, channels, mask, hist, 2, histSize, ranges);

	// Apply histogram backprojection to an input image

	Mat src, src_ycrcb;
	src = imread("kids.png", IMREAD_COLOR);
	cvtColor(src, src_ycrcb, COLOR_BGR2YCrCb);

	Mat backproj;
	calcBackProject(&src_ycrcb, 1, channels, hist, backproj, ranges, 1, true);

	imshow("src", src);
	imshow("backproj", backproj);
	waitKey(0);

	return 0;
}

C++ Code 출처 : OpenCV 4로 배우는 컴퓨터 비전과 머신 러닝 - 황선규 저


'OpenCV' 카테고리의 다른 글

ch10 colorOp  (0) 2024.05.21
ch10 coloreq  (0) 2024.05.21
ch09 hough  (0) 2024.05.20
ch09 edges  (0) 2024.05.20
ch08 perspective  (0) 2024.05.20