在OpenC中正确复制轮廓的内部区域

2024-06-16 14:56:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用opencv和python,我正在尝试检测一些游戏卡和 我卡住了。我想复制countor的内部区域。我写了这个代码:

检测轮廓


    import cv2
    import numpy as np

    image = frame of a video
    gray = cv2.cvtColor(image, 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_EXTERNAL, 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 > 150) and (not is_in_array(card, contourns_to_draw)):
            rect = cv2.boundingRect(card)
            x, y, w, h = rect
            if h > w:
                contourns_to_draw.append(card)

    img = cv2.drawContours(image, contourns_to_draw, -1, (0, 255, 0), 1)

复制轮廓区域并创建新图像


for i, contour in enumerate(contourns_to_draw):
        peri = cv2.arcLength(contour, True)

        approx = cv2.approxPolyDP(contour, 0.01 * peri, True)

        h = np.array([[0, 0], [449, 0], [449, 449], [0, 449]], np.float32)

        if  len(approx) != 4 :
            continue
        else:
            transform = cv2.getPerspectiveTransform(approx.astype(np.float32), h)


        warp = cv2.warpPerspective(image, transform, (450, 450))
        # warp = rotateImage(warp, -90)
        warp = cv2.flip(warp, +1)

        dominance_color = bincount_app(warp)
        cv2.imshow("Show Boxes", warp)
        key = cv2.waitKey(0) & 0xFF

当我在像这样的视频帧上使用这个代码时

enter image description here

轮廓检测工作良好,但当它从轮廓区域创建一个新图像时,输出是一个随机旋转的新图像,有时也会翻转

轮廓内部区域图像的示例 enter image description here

我的目标是要有一个没有旋转,也没有翻转的图像,有时输出是正确的,但其他时候是像我添加的图像,我不明白是什么产生了不同的输出。你知道吗


Tags: to图像imagetrue区域npcardcv2