OpenCV templateMatching not working properly on images with simple black and white shapes

47 Views Asked by At

I'm using Python with OpenCV to identify specific shapes in images, but the code is incorrectly identifying the right places, resulting in false positives.

Here is the method I use to identify matches:

def set_markers(self):
    
        correlation_img = cv2.matchTemplate(self.base_image,self.template,cv2.TM_SQDIFF_NORMED)

        corrcopy = correlation_img.copy()

        self.markers = MarkerList(self.template)
        for i in range(0, self.markers_amount):      
            # get max value and location of max
            _, max_val, _, max_loc = cv2.minMaxLoc(corrcopy)

            if max_val > 0.95:
                marker = Marker(max_loc[0],max_loc[1], self.template)
                self.markers.add(marker)  
                
                cv2.circle(corrcopy, (marker.x1,marker.y1), self.match_radius, 0, -1)
                i = i + 1               
            else:
                break

        if self.markers.length() != 4:
            raise Exception(f"Número de marcadores detectados difere de 4: {self.markers.length()} encontrados")

Note: The MarkerList and Marker classes are simply abstractions of the positions obtained from template matching. As indicated in the code, they aren't relevant to this issue. The self.template and self.base_image variables correspond to the following images:

enter image description hereenter image description here

While debugging, I noticed that the threshold (thresh) values of the match points are all 1.0, yet the result is still false positives. The resulting image is as follows (later in the code, I crop the area around the markers. The result is the areas inside the red rectangles, connected by the yellow line): enter image description here

I've tried saving the correlation image to check the result, but it turned out to be completely black.

Notes:

I've experimented with different OpenCV methods like TM_CCORR_NORMED and TM_CCOEFF_NORMED, but didn't achieve the desired results; the threshold was set at 0.3 with more than 100 matches...

If I remove the black rectangles inside the table in the image, the code works. Here is the result:

enter image description here

The current approach was successful with different base images. If you check my profile, you'll see I've asked a similar question using a more complex image, and I got something close to the code I provided at the beginning of this question. For that situation, it worked perfectly. Here are the image and the result:

enter image description here

enter image description here

0

There are 0 best solutions below