0

I'm struggling with my last thesis. The purpose of this code is to identifying image (which given the template too) using Template matching method that provided by OpenCV.

This code supposed to be find object that having the same form with the template, but when I run it with different image with different template(which relate to the input image) it doesn't work how it supposed to be.

Wrap it up, the problem is when the code trying to scanning the image and searching for the location in image which having the same form with the template.

So this code need to change how it scanning the image fully and matching it with the template, but I dont know how

Please help:(

import numpy as np
import argparse
import imutils
import glob
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-t", "--template", required=True, help="Path to template image")
ap.add_argument("-i", "--images", required=True,
    help="Path to images where template will be matched")
ap.add_argument("-v", "--visualize",
    help="Flag indicating whether or not to visualize each iteration")
args = vars(ap.parse_args())

# load the image image, convert it to grayscale, and detect edges
template = cv2.imread(args["template"])
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
template = cv2.Canny(template, 50, 200)
(tH, tW) = template.shape[:2]
cv2.imshow("Template", template)

# loop over the images to find the template in
for imagePath in glob.glob(args["images"]):
    # load the image, convert it to grayscale, and initialize the
    # bookkeeping variable to keep track of the matched region
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    found = None


    # loop over the scales of the image
    for scale in np.linspace(0.2, 1.0, 20)[::-1]:
        # resize the image according to the scale, and keep track
        # of the ratio of the resizing
        resized = imutils.resize(gray, width = int(gray.shape[1] * scale))
        r = gray.shape[1] / float(resized.shape[1])

        # if the resized image is smaller than the template, then break
        # from the loop
        if resized.shape[0] < tH or resized.shape[1] < tW:
            break

        # detect edges in the resized, grayscale image and apply template
        # matching to find the template in the image
        edged = cv2.Canny(resized, 50, 200)
        result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
        (_, maxVal, _, maxLoc) = cv2.minMaxLoc(result)

        # check to see if the iteration should be visualized
        if args.get("visualize", False):
            # draw a bounding box around the detected region
            clone = np.dstack([edged, edged, edged])
            cv2.rectangle(clone, (maxLoc[0], maxLoc[1]),
                (maxLoc[0] + tW, maxLoc[1] + tH), (0, 0, 255), 2)
            cv2.imshow("Visualize", clone)
            cv2.waitKey(0)

        # if we have found a new maximum correlation value, then ipdate
        # the bookkeeping variable
        if found is None or maxVal > found[0]:
            found = (maxVal, maxLoc, r)

    # unpack the bookkeeping varaible and compute the (x, y) coordinates
    # of the bounding box based on the resized ratio
    (_, maxLoc, r) = found
    (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r))
    (endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r))

    # draw a bounding box around the detected result and display the image
    cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
    cv2.imshow("Image", image)
    cv2.waitKey(0)

the image which in gray is the template, and the red square in image are the result of the match template code which is very wrong

  • Hi Meldea Nophia, and welcome at Stack Overflow :-). I fear that your question is too unspecific to obtain really helpful answers. Please describe in more detail what the script is supposed to do and how it fails. Also, you will probably need to break down the script to a minimal reproducible example, such that we can verify the behavior and play with it. Right, now, we cannot even run it because there are file references in the script that we don't have on our computers :-( – Amos Egel May 21 '20 at 09:28
  • okay, I'm sorry, let me edit it – Melda Nophia May 21 '20 at 09:57
  • Could you describe a use case (maybe upload some images)? How do you call the script? What is the expected result? What happens instead? I understand that for some template and image it works (can you upload and show how it looks?) but for another template and image it doesn't (how does it look like, then?). – Amos Egel May 21 '20 at 10:27
  • I'm calling the script by using on command prompt python match.py -t template.jpg -i input.jpg match.py is the file name for some image and template that works, you can see on this link https://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/ the expected result you can see on that link too – Melda Nophia May 21 '20 at 11:20
  • and, I changed something on the code, u should try it – Melda Nophia May 21 '20 at 11:47

0 Answers0