본문 바로가기

OpenCV

ch13 template

#python

import cv2
import numpy as np

def template_matching():
    img = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch13\\template\\circuit.bmp", cv2.IMREAD_COLOR)
    templ = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch13\\template\\crystal.bmp", cv2.IMREAD_COLOR)

    if img is None or templ is None:
        print("Image load failed!")
        return

    img = img + np.array([50, 50, 50])

    noise = np.zeros_like(img, dtype=np.int32)
    cv2.randn(noise, 0, 10)
    img = cv2.add(img, noise, dtype=cv2.CV_8UC3)

    res = cv2.matchTemplate(img, templ, cv2.TM_CCOEFF_NORMED)
    res_norm = cv2.normalize(res, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)

    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(res)
    print("maxVal:", maxVal)
    print(maxLoc)

    cv2.rectangle(img, [maxLoc[0],maxLoc[1], templ.shape[1], templ.shape[0]], [0, 0, 255], 2)

    cv2.imshow("templ", templ)
    cv2.imshow("res_norm", res_norm)
    cv2.imshow("img", img)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    template_matching()

// C++

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

using namespace cv;
using namespace std;

void template_matching();

int main()
{
	template_matching();

	return 0;
}

void template_matching()
{
	Mat img = imread("circuit.bmp", IMREAD_COLOR);
	Mat templ = imread("crystal.bmp", IMREAD_COLOR);

	if (img.empty() || templ.empty()) {
		cerr << "Image load failed!" << endl;
		return;
	}

	img = img + Scalar(50, 50, 50);

	Mat noise(img.size(), CV_32SC3);
	randn(noise, 0, 10);
	add(img, noise, img, Mat(), CV_8UC3);

	Mat res, res_norm;
	matchTemplate(img, templ, res, TM_CCOEFF_NORMED);
	normalize(res, res_norm, 0, 255, NORM_MINMAX, CV_8U);

	double maxv;
	Point maxloc;
	minMaxLoc(res, 0, &maxv, 0, &maxloc);
	cout << "maxv: " << maxv << endl;

	rectangle(img, Rect(maxloc.x, maxloc.y, templ.cols, templ.rows), Scalar(0, 0, 255), 2);

	imshow("templ", templ);
	imshow("res_norm", res_norm);
	imshow("img", img);

	waitKey(0);
	destroyAllWindows();
}

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


'OpenCV' 카테고리의 다른 글

ch14 keypoints  (0) 2024.05.22
ch14 corners  (0) 2024.05.22
ch13 QRCode  (0) 2024.05.21
ch13 hog  (0) 2024.05.21
ch13 cascade  (0) 2024.05.21