【Python】四角形の重複した部分
matplotlibでRectangleを2つ描画する時に重複している部分の四角形を描画する.
intersectionというらしい.
まずは適当な四角形を作る.
recs=[] recs.append(matplotlib.patches.Rectangle((10,10),300,60, color='r', fill=False)) recs.append(matplotlib.patches.Rectangle((5,5),20,20, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((150,5),20,20, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((300,5),20,20, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((5,55),20,20, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((150,55),20,20, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((300,55),20,20, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((200,90),100,90, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((100,100),300,20, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((100,200),100,60, color='b', fill=False)) recs.append(matplotlib.patches.Rectangle((80,160),160,130, color='b', fill=False))
描画する.
fig = plt.figure() ax = fig.add_subplot(1,1,1,xlim =500,ylim=300) for rec in recs: ax.add_patch(rec) plt.show()
それぞれの四角形に関して,重なってるかどうか総当りで判定する.
重なってるならh=1,重なってないならh=0.
for f in recs: for s in recs: if f == s: pass else: h = f.get_path().intersects_path(s.get_path())
重なっている四角形を再度作りなおす.
nr = [] if h == 1: fx = f.get_x() fy = f.get_y() fw = f.get_width() fh = f.get_height() sx = s.get_x() sy = s.get_y() sw = s.get_width() sh = s.get_height() if fx <= sx and fy <= sy and fx+fw <= sx+sw and sx <= fx+fw and fy+fh <= sy+sh and fy+fh >= sy: nr.append(matplotlib.patches.Rectangle((sx,sy),fx+fw-sx,fy+fh-sy,color='gray',fill=True,alpha =0.9)) if fx >= sx and fy <= sy and fx+fw >= sx+sw and fx <= sx+sw and fy+fh <= sy+sh and fy+fh >= sy: nr.append(matplotlib.patches.Rectangle((fx,sy),sx+sw-fx,fy+fh-sy,color='green',fill=True,alpha =0.9)) if fx <= sx and fy <= sy and fx+fw >= sx+sw and fy+fh <= sy+sh and fy+fh >= sy: nr.append(matplotlib.patches.Rectangle((sx,sy),sw,fy+fh-sy,color='black',fill=True,alpha =0.9)) if fx <= sx and fy >= sy and fx+fw >= sx+sw and sy+sh >= fy and sy+sh<=fy+fh: nr.append(matplotlib.patches.Rectangle((sx,fy),sw,sy+sh-fy,color='r',fill=True,alpha =0.9)) if fx > sx and fy >= sy and fx+fw <= sx+sw and fy+fh <= sy+sh: nr.append(matplotlib.patches.Rectangle((fx,fy),fw,fh,color='c',fill=True,alpha =0.9)) if sx < fx and fy <= sy and sy <= fy+fh and fy+fh >= sy+sh and sx+sw >= fx+fw: nr.append(matplotlib.patches.Rectangle((fx,sy),fw,sh,color='y',fill=True,alpha =0.9))
それを描画する.