| 44 | } |
| 45 | |
| 46 | static void templateMatchingDemo(bool console) { |
| 47 | // Load image |
| 48 | array img_color; |
| 49 | if (console) |
| 50 | img_color = loadImage(ASSETS_DIR "/examples/images/square.png", true); |
| 51 | else |
| 52 | img_color = loadImage(ASSETS_DIR "/examples/images/man.jpg", true); |
| 53 | |
| 54 | // Convert the image from RGB to gray-scale |
| 55 | array img = colorSpace(img_color, AF_GRAY, AF_RGB); |
| 56 | dim4 iDims = img.dims(); |
| 57 | std::cout << "Input image dimensions: " << iDims << std::endl << std::endl; |
| 58 | // For visualization in ArrayFire, color images must be in the [0.0f-1.0f] |
| 59 | // interval |
| 60 | |
| 61 | // extract a patch from input image |
| 62 | unsigned patch_size = 100; |
| 63 | array tmp_img = |
| 64 | img(seq(100, 100 + patch_size, 1.0), seq(100, 100 + patch_size, 1.0)); |
| 65 | array result = |
| 66 | matchTemplate(img, tmp_img); // Default disparity metric is |
| 67 | // Sum of Absolute differences (SAD) |
| 68 | // Currently supported metrics are |
| 69 | // AF_SAD, AF_ZSAD, AF_LSAD, AF_SSD, |
| 70 | // AF_ZSSD, ASF_LSSD |
| 71 | array disp_img = img / 255.0f; |
| 72 | array disp_tmp = tmp_img / 255.0f; |
| 73 | array disp_res = normalize(result); |
| 74 | |
| 75 | unsigned minLoc; |
| 76 | float minVal; |
| 77 | min<float>(&minVal, &minLoc, disp_res); |
| 78 | std::cout << "Location(linear index) of minimum disparity value = " |
| 79 | << minLoc << std::endl; |
| 80 | |
| 81 | if (!console) { |
| 82 | // Draw a rectangle on input image where the template matches |
| 83 | array marked_res = tile(disp_img, 1, 1, 3); |
| 84 | drawRectangle(marked_res, minLoc % iDims[0], minLoc / iDims[0], |
| 85 | patch_size, patch_size); |
| 86 | |
| 87 | std::cout << "Note: Based on the disparity metric option provided to " |
| 88 | "matchTemplate function\n" |
| 89 | "either minimum or maximum disparity location is the " |
| 90 | "starting corner\n" |
| 91 | "of our best matching patch to template image in the " |
| 92 | "search image" |
| 93 | << std::endl; |
| 94 | |
| 95 | af::Window wnd("Template Matching Demo"); |
| 96 | |
| 97 | // Previews color image with green crosshairs |
| 98 | while (!wnd.close()) { |
| 99 | wnd.setColorMap(AF_COLORMAP_DEFAULT); |
| 100 | wnd.grid(2, 2); |
| 101 | wnd(0, 0).image(disp_img, "Search Image"); |
| 102 | wnd(0, 1).image(disp_tmp, "Template Patch"); |
| 103 | wnd(1, 0).image(marked_res, "Best Match"); |
no test coverage detected