• 计算图片中两个任意形状多边形相交部分的大小


    一张图片中两个任意多边形相交的面积计算方法。本文参考https://blog.csdn.net/PanYHHH/article/details/110940428;加了一个简单的示例,也对代码做了一点清淅化。原博客中还有其他链接,是C代码,没有看原理,但以下代码也可以很容易转成C代码,用opencv 来实现。

    import cv2
    import numpy as np
    ImH=200
    ImW=200
    Polygon1=np.array([[0,0],[100,0],[100,100],[0,100]],dtype=np.int32)
    Polygon2=np.array([[50,50],[150,50],[150,150],[50,150]],dtype=np.int32)
    ImShape=(ImH,ImW,3)
    def DrawPolygon(ImShape,Polygon,Color):
        Im = np.zeros(ImShape, np.uint8)    
        cv2.fillPoly(Im, [Polygon], Color)  # 这个函数可以画凹凸多边形,所以这个更稳妥
        #cv2.fillConvexPoly(Im,Polygon,Color) #这行代码也是可以的,因为是凸多边形
        return Im
    Im1 = DrawPolygon(ImShape, Polygon1, (255, 0, 0))
    Im2 = DrawPolygon(ImShape, Polygon2, (0, 255, 0))
    plt.subplot(311)
    plt.imshow(Im1)
    plt.subplot(312)
    plt.imshow(Im2)
    
    Im1 =DrawPolygon(ImShape[:-1],Polygon1,122)#多边形1区域填充为122
    Im2 =DrawPolygon(ImShape[:-1], Polygon2, 133)#多边形2区域填充为133
    Im = Im1 + Im2
    ret, OverlapIm = cv2.threshold(Im, 200, 255, cv2.THRESH_BINARY)#根据上面的填充值,因此新图像中的像素值为255就为重叠地方
    plt.subplot(313)
    plt.imshow(OverlapIm,cmap="gray")
    IntersectArea=np.sum(np.greater(OverlapIm, 0))#求取两个多边形交叠区域面积
    print("cumstom calcuate area:{}\n".format(IntersectArea))
    
    #下面使用opencv自带的函数求取一下,最为对比
    contours, hierarchy = cv2.findContours(OverlapIm,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    contourArea=cv2.contourArea(contours[0])
    print('contourArea={}\n'.format(contourArea))
    perimeter = cv2.arcLength(contours[0], True)
    print('contourPerimeter={}\n'.format(perimeter))
    RealContourArea=contourArea+perimeter
    print('RealContourArea={}\n'.format(RealContourArea))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    结果如下图
    在这里插入图片描述

  • 相关阅读:
    SSM-XML整合
    Ventoy制作PE启动盘 和 使用VMware测试启动盘
    springboot实现无数据库启动
    GEE|时间序列分析(四)
    关于RSA加解密的异常 javax.crypto.BadPaddingException: block incorrect
    “酱香拿铁”背后的心理学、经济学原理和给我们的启示
    如何将转换器应用于时序模型
    Python 异步网络编程实战
    tomcat的安装和解析
    Python开发技术—函数设计1
  • 原文地址:https://blog.csdn.net/u011119817/article/details/134397685