Home cv2.matchShapes() always returns 0.0
Reply: 0

cv2.matchShapes() always returns 0.0

user2043 Published in April 25, 2018, 12:32 pm

I've been trying to compare contours of a livefeed with the contours of an image using cv2.matchshapes(). I'm using the following image

This is the code I'm using (sorry for the sloppy formatting):

import numpy as np
import cv2

cap = cv2.VideoCapture(2)
img1 = cv2.imread('prod1_gray.jpg',0)

ret, thresh_img1 = cv2.threshold(img1, 230, 255, cv2.THRESH_BINARY)

kernel = np.ones((3, 3), np.uint8)
thresh_img1 = cv2.dilate(thresh_img1, kernel, iterations=2)
thresh_img1 = cv2.erode(thresh_img1, kernel, iterations=3)

_, contours_img1, hierarchy = cv2.findContours(thresh_img1, 
if contours_img1:
    cntimg = contours_img1[0]

while True:
    _, frame  = cap.read()
    frame = frame[127:470, 80:550]
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(frame_gray, 230, 255, cv2.THRESH_BINARY)

    kernel = np.ones((3, 3), np.uint8)
    thresh = cv2.dilate(thresh, kernel, iterations=2)
    thresh = cv2.erode(thresh, kernel, iterations=3)

    _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if contours:
        cnt = contours[0]
        area = cv2.contourArea(cnt)
        if area > 30:
            cv2.drawContours(frame, contours, -1, (0, 255, 255), 3)

        ret = cv2.matchShapes(cnt[0], cntimg[0], 1, 0.0)

    cv2.imshow("Original", frame)
    cv2.imshow("gray", frame_gray)

    k = cv2.waitKey(30)
    if k == 27:
        cv2.imwrite("pen.jpg", img1)
        print("cntimg, ",cntimg[0])
        print("cnt, ",cnt[0])


For some reason, the cv2.matchShapes() always outputs 0.0, wether nothing is in front of the camera (no contours) or a random object like a pen. While it should be outputting a number, since the pen has a different shape than the original object.

What am I doing wrong?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.480016 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO