【问题标题】:Extracting polygon given coordinates from an image using OpenCV使用OpenCV从图像中提取多边形给定坐标
【发布时间】:2015-09-03 05:53:25
【问题描述】:

我有如下一组点:

     <data:polygon>
                            <data:point x="542" y="107"/>
                            <data:point x="562" y="102"/>
                            <data:point x="582" y="110"/>
                            <data:point x="598" y="142"/>
                            <data:point x="600" y="192"/>
                            <data:point x="601" y="225"/>
                            <data:point x="592" y="261"/>
                            <data:point x="572" y="263"/>
                            <data:point x="551" y="245"/>
                            <data:point x="526" y="220"/>
                            <data:point x="520" y="188"/>
                            <data:point x="518" y="152"/>
                            <data:point x="525" y="127"/>
                            <data:point x="542" y="107"/
 </data:polygon>

我想在图像中绘制由这些点定义的多边形,然后提取它。如何使用 OpenCV 和 python 做到这一点?

【问题讨论】:

    标签: python image opencv image-processing polygon


    【解决方案1】:

    使用cv2.fillConvexPoly 以便您可以指定一个二维点数组并定义一个掩码,该掩码填充由这些点定义的形状,在掩码中为白色。在多边形中定义的点是凸的(因此得名fillConvexPoly)时,应该发出一些公平的警告。

    然后我们可以将其转换为布尔蒙版,并使用它来索引您的图像以提取您想要的像素。下面的代码生成一个名为mask 的数组,它将包含您要从图像中保存的像素的布尔掩码。此外,数组out 将包含由多边形定义的所需提取子图像。请注意,图像被初始化为完全黑暗,并且唯一要复制的像素是多边形定义的像素。

    假设实际图像称为img,并假设您的xy 点表示图像中的水平和垂直坐标,您可以执行以下操作:

    import numpy as np
    import cv2
    
    pts = np.array([[542, 107], [562, 102], [582, 110], [598, 142], [600, 192], [601, 225], [592, 261], [572, 263], [551, 245], [526, 220], [520, 188], [518, 152], [525, 127], [524, 107]], dtype=np.int32)
    
    mask = np.zeros((img.shape[0], img.shape[1]))
    
    cv2.fillConvexPoly(mask, pts, 1)
    mask = mask.astype(np.bool)
    
    out = np.zeros_like(img)
    out[mask] = img[mask]
    

    out 除了要复制的区域外,都应该是黑色的。如果要显示此图像,可以执行以下操作:

    cv2.imshow('Extracted Image', out)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    这将显示从多边形点提取的图像并等待您按下一个键。看完图像后,只要显示窗口有焦点,就可以按任意键。

    如果您想保存此图像到文件,请执行以下操作:

    cv2.imwrite('output.png', out)
    

    这会将图像保存到名为output.png 的文件中。我指定 PNG 格式是因为它是无损的。


    作为一个简单的测试,让我们定义一个白色图像300 x 700,它远远超出了您定义的最大坐标。让我们提取由该多边形定义的区域并显示输出的样子。

    img = 255*np.ones((300, 700, 3), dtype=np.uint8)
    

    使用上面的测试图像,我们得到这个图像:

    编辑

    如果您想翻译提取的图像使其位于中间,然后在边界框周围放置一个正方形,我可以建议的一个技巧是使用cv2.remap 来翻译图像。完成后,使用cv2.rectangle 绘制正方形。

    cv2.remap 的工作原理是,对于输出中的每个像素,您需要指定要访问源图像中像素位置的空间坐标。因为您最终将输出移动到图像的中心,所以您需要为目标图像中的每个xy 位置添加一个偏移量以获取源像素。

    要找出移动图像的正确偏移量,只需找出多边形的质心,平移多边形以使质心位于原点,然后重新平移使其位于图像的中心。

    使用我们上面定义的变量,您可以通过以下方式找到质心:

    (meanx, meany) = pts.mean(axis=0)
    

    一旦找到质心,您将获取所有点并减去该质心,然后添加适当的坐标以重新平移到图像的中心。可以通过以下方式找到图像的中心:

    (cenx, ceny) = (img.shape[1]/2, img.shape[0]/2)
    

    将坐标转换为整数也很重要,因为像素坐标如下:

    (meanx, meany, cenx, ceny) = np.floor([meanx, meany, cenx, ceny]).astype(np.int32)
    

    现在要计算出偏移量,就像我们之前谈到的那样:

    (offsetx, offsety) = (-meanx + cenx, -meany + ceny)
    

    现在,翻译您的图像。您需要为输出图像中的每个像素定义一个映射,其中对于目标图像中的每个点(x,y),您需要提供从源中采样的位置。我们计算的偏移量将每个源像素转换为目标位置。因为我们正在执行相反,对于每个目标像素,我们正在寻找要从哪个源像素采样,我们必须减去偏移量,而不是添加。因此,首先正常定义(x,y)点的网格,然后减去偏移量。完成后,翻译图像:

    (mx, my) = np.meshgrid(np.arange(img.shape[1]), np.arange(img.shape[0]))
    ox = (mx - offsetx).astype(np.float32)
    oy = (my - offsety).astype(np.float32)
    out_translate = cv2.remap(out, ox, oy, cv2.INTER_LINEAR)
    

    如果我们在上面的例子中显示out_translate,这就是我们得到的:


    酷!现在是时候在此图像上绘制矩形了。您所要做的就是找出矩形的左上角和右下角。这可以通过获取多边形的左上角和右下角并添加偏移量以将这些点移动到图像的中心来完成:

    topleft = pts.min(axis=0) + [offsetx, offsety]
    bottomright = pts.max(axis=0) + [offsetx, offsety]
    cv2.rectangle(out_translate, tuple(topleft), tuple(bottomright), color=(255,0,0))
    

    如果我们显示这张图片,我们会得到:


    上面的代码在居中的图像周围画了一个蓝色的矩形。因此,从开始(提取像素区域)到结束(平移和绘制矩形)的完整代码是:

    # Import relevant modules
    import numpy as np
    import cv2
    
    # Define points
    pts = np.array([[542, 107], [562, 102], [582, 110], [598, 142], [600, 192], [601, 225], [592, 261], [572, 263], [551, 245], [526, 220], [520, 188], [518, 152], [525, 127], [524, 107]], dtype=np.int32)
    
    ### Define image here
    img = 255*np.ones((300, 700, 3), dtype=np.uint8)
    
    # Initialize mask
    mask = np.zeros((img.shape[0], img.shape[1]))
    
    # Create mask that defines the polygon of points
    cv2.fillConvexPoly(mask, pts, 1)
    mask = mask.astype(np.bool)
    
    # Create output image (untranslated)
    out = np.zeros_like(img)
    out[mask] = img[mask]
    
    # Find centroid of polygon
    (meanx, meany) = pts.mean(axis=0)
    
    # Find centre of image
    (cenx, ceny) = (img.shape[1]/2, img.shape[0]/2)
    
    # Make integer coordinates for each of the above
    (meanx, meany, cenx, ceny) = np.floor([meanx, meany, cenx, ceny]).astype(np.int32)
    
    # Calculate final offset to translate source pixels to centre of image
    (offsetx, offsety) = (-meanx + cenx, -meany + ceny)
    
    # Define remapping coordinates
    (mx, my) = np.meshgrid(np.arange(img.shape[1]), np.arange(img.shape[0]))
    ox = (mx - offsetx).astype(np.float32)
    oy = (my - offsety).astype(np.float32)
    
    # Translate the image to centre
    out_translate = cv2.remap(out, ox, oy, cv2.INTER_LINEAR)
    
    # Determine top left and bottom right of translated image
    topleft = pts.min(axis=0) + [offsetx, offsety]
    bottomright = pts.max(axis=0) + [offsetx, offsety]
    
    # Draw rectangle
    cv2.rectangle(out_translate, tuple(topleft), tuple(bottomright), color=(255,0,0))
    
    # Show image, wait for user input, then save the image
    cv2.imshow('Output Image', out_translate)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite('output.png', out_translate)
    

    【讨论】:

    • 很好的答案!谢谢。
    • 完全没问题!祝你好运!
    • 啊是的,这应该不是问题。一会儿我会回答的。我目前正在下班回家的路上。
    • 很抱歉。我会在几个小时内修改它。昨晚很忙。
    • 完美!这个答案就像一个简短的教程。非常感谢雷。
    猜你喜欢
    • 2020-09-02
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2013-12-26
    • 2014-08-02
    相关资源
    最近更新 更多