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

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

python 复制代码
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))

结果如下图