Skip to content

Instantly share code, notes, and snippets.

@ikarino
Last active August 29, 2015 14:09
Show Gist options
  • Save ikarino/b93826e73a56d3c2a36e to your computer and use it in GitHub Desktop.
Save ikarino/b93826e73a56d3c2a36e to your computer and use it in GitHub Desktop.
適当な画像(テンプレート)を適当な範囲で適当な回数検出する
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vector>
int main(int argc, char** argv) {
cv::VideoCapture cap(1);
if(!cap.isOpened()) {
std::cout << "Camera couldn't open !\n";
return -1;
}
cv::namedWindow("window", 1);
// テンプレートとなる画像
std::vector<cv::Mat> img;
img.push_back(cv::imread("./0.png", 1));
img.push_back(cv::imread("./1.png", 1));
img.push_back(cv::imread("./3.png", 1));
img.push_back(cv::imread("./4.png", 1));
img.push_back(cv::imread("./9.png", 1));
// 適当な範囲 (MacBookAirのカメラは1280x720だった)
cv::Rect search_range = cv::Rect(0, 600, 500, 100);
// 適当な回数
int times_to_detect = 4;
// 適当な精度
double detection_accuracy = 0.7;
while(true) {
cv::Mat frame;
cap >> frame;
cv::Mat frame0 = frame(search_range); // ROI
cv::rectangle(frame, search_range, cv::Scalar(0, 0, 255)); // red
for(size_t j = 0; j < img.size(); j++) {
cv::Mat result_img;
cv::matchTemplate(frame0, img[j], result_img, CV_TM_CCOEFF_NORMED);
for(int i = 0; i < times_to_detect; i++) {
cv::Point max_pt;
double maxVal;
cv::minMaxLoc(result_img, NULL, &maxVal, NULL, &max_pt);
if(maxVal < detection_accuracy) break;
cv::Rect roi_rect(0, 0, img[j].cols, img[j].rows);
roi_rect.x = max_pt.x + search_range.x;
roi_rect.y = max_pt.y + search_range.y;
cv::rectangle(frame, roi_rect, cv::Scalar(0, 255, 255)); // yellow
}
}
cv::imshow("window", frame);
cv::waitKey(10);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment