getPerspectiveTransform断言错误openCV

时间:2019-07-15 15:53:44

标签: python opencv

我正在用opencv创建一个脚本来检测游戏卡。作为输入图像,我给这个enter image description here

我已经写了这个用于检测卡的轮廓

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

检测到纸牌轮廓,但是当我尝试获取单张纸牌图像时,为了了解什么是纸牌,它给了我一个错误。当我调用方法transform = cv2.getPerspectiveTransform(approx, h)时出现错误,错误是这个

错误

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'

我正在跟踪this guide,并试图了解他的步调是如何进行的,但是我被这条线所困。

我只想复制卡片轮廓内的区域,另存为另一张图像,然后将该图像与其他图像进行Campare处理以检测出什么卡片。

1 个答案:

答案 0 :(得分:1)

问题是approxnp.int32。所以你想做

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