2016-08-20 510 views
2

我試着用這裏顯示的算法面積:https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area查找多個重疊的矩形的交集在Python

然而,該算法只涉及只發現兩個重疊的矩形的面積。

如果我知道每個矩形的長度和寬度,我將如何繼續尋找說3或4或5等交疊矩形的交點的區域?

+2

您是否在尋找_n_矩形的聯合,或交集?如果相交,你想計算_any_重疊的區域,還是隻在矩形重疊的地方? –

+0

交叉點,其中所有的矩形重疊 – Falcon2908

+2

請編輯您的問題以包含這樣的重要細節,這樣人們就不會浪費時間解決錯誤的問題。 (請注意,您收到的第一個答案以「我假設您想要查找**聯盟的區域** ...」開頭)。 –

回答

6

Shapely對於像這樣的東西是一個很好的庫。

from shapely.geometry import box 

# make some rectangles (for demonstration purposes and intersect with each other) 
rect1 = box(0,0,5,2) 
rect2 = box(0.5,0.5,3,3) 
rect3 = box(1.5,1.5,4,6) 

rect_list = [rect1, rect2, rect3] 

# find intersection of rectangles (probably a more elegant way to do this) 
for rect in rect_list[1:]: 
    rect1 = rect1.intersection(rect) 
intersection = rect1 

想象這裏發生了什麼。我繪製矩形和它們的交集:

from matplotlib import pyplot as plt 
from matplotlib.collections import PatchCollection 
from matplotlib.patches import Polygon 

# plot the rectangles before and after merging 

patches = PatchCollection([Polygon(a.exterior) for a in rect_list], facecolor='red', linewidth=.5, alpha=.5) 
intersect_patch = PatchCollection([Polygon(intersection.exterior)], facecolor='red', linewidth=.5, alpha=.5) 

# make figure 
fig, ax = plt.subplots(1,2, subplot_kw=dict(aspect='equal')) 
ax[0].add_collection(patches, autolim=True) 
ax[0].autoscale_view() 
ax[0].set_title('separate polygons') 
ax[1].add_collection(intersect_patch, autolim=True) 
ax[1].set_title('intersection = single polygon') 
ax[1].set_xlim(ax[0].get_xlim()) 
ax[1].set_ylim(ax[0].get_ylim()) 
plt.show() 

enter image description here

+0

如何在mac OS X上安裝shapely.geometry? – Falcon2908

+1

看文檔:https://pypi.python.org/pypi/Shapely。 如果您使用的是Anaconda dist,則可以在命令行中使用'conda install shapely'(推薦)。 – benten

+0

好吧,我用conda來執行那個安裝代碼行,現在說「用法:安裝[-bCcpSsv] [-B後綴] [-f標誌] [-g組] [-m模式] [-o所有者] file1 file2 install [-bCcpSsv] [-B後綴] [-f標誌] [-g組] [-m模式] [-o所有者] file1 ... fileN目錄 install -d [-v] [ -g組] [-m模式] [-o所有者]目錄...「我現在要做什麼 – Falcon2908