Mat.C
Mat.C

Reputation: 1429

getPerspectiveTransform Assertion error openCV

I'm creating a script with opencv for detect game cards. As input image i give this one enter image description here

And i've wrote this for detect the cards contours

import cv2
import numpy as np

im = cv2.imread('/home/pero/PycharmProjects/image-recognition/python/cards.png')
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (1, 1), 1000)
flag, thresh = cv2.threshold(blur, 120, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)


contourns_to_draw = []

# filter the cards contour
for i in range(len(contours)):
    card = contours[i]
    peri = cv2.arcLength(card, True)
    if peri > 800:
        contourns_to_draw.append(card)

img = cv2.drawContours(im, contourns_to_draw, -1, (0, 255, 0), 3)
cv2.imshow("Show Boxes", img)
key = cv2.waitKey(0) & 0xFF

# Should create a new image by the given card contour ( NOT WORK )
for i, contour in enumerate(contourns_to_draw):

    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
    rect = cv2.minAreaRect(contour)
    r = cv2.boxPoints(rect)

    h = np.array([[0, 0], [449, 0], [449, 449], [0, 449]], np.float32)
    transform = cv2.getPerspectiveTransform(approx, h)
    warp = cv2.warpPerspective(im, transform, (450, 450))


    # cv2.imshow("Show Boxes", cropped)
    # key = cv2.waitKey(0) & 0xFF
    # if key == 27:
    #     break
    # cv2.destroyAllWindows()
    break

The cards contours are detected but when i try to get the single card image, for understand what card is, it gives me an error. The error is raise when i call the method transform = cv2.getPerspectiveTransform(approx, h) and the error is this one

ERROR

transform = cv2.getPerspectiveTransform(approx, h)
cv2.error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/imgwarp.cpp:3157:
error: (-215:Assertion failed) src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4 in function 'getPerspectiveTransform'

I'm following this guide and trying to understand whet he does step by step but i got stuck with that line.

I want only to copy the area inside the card contour ,save it as another image and after campare that image with other images for detect what card is.

Upvotes: 2

Views: 3196

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

The problem is that approx is np.int32. So you want to do:

transform = cv2.getPerspectiveTransform(approx.astype(np.float32), h)

Upvotes: 3

Related Questions