遇到个要解决的问题,图片中有若干个矩形,需要将所有相交的矩形用一个大矩形将它们替代:
1、这种方法能快速找到相邻的两个矩形
#判断patch中是否有重叠,有则合为一个,取两个的并集
#算法思路:矩形中心坐标任一轴之差大于该轴方向的二分之一边之和; (A - 1)!
#先进行排序,左右排序,A; 再进行相邻距离差计算,如果 ( x2 -x1 ) < w1 距离在之内,则比较上下,A*A
i = -1
patch = []
extend_patch = []
Centroid = []
watches = sorted(watches, key=takeFrist) #指定第一个元素进行顺序排序
print watches
print len(watches)
for (x,y,w,h) in watches:
cv2.rectangle(img, (x, y), (x + w+2, y + h+2), (0, 0, 255), 1)
for count_ in range(len(watches)):
x,y,w,h = watches[count_]
print watches[count_]
if count_ + 1 >= len(watches):
pass
else:
if (watches[count_+1][0] - watches[count_][0]) > watches[count_][2]:#x方向
pass
else:
if abs(watches[count_+1][1] - watches[count_][1]) > min(watches[count_][3],watches[count_+1][3]):
pass
else:
x = x
w = watches[count_+1][2] + (watches[count_+1][0] - x)
if y > watches[count_+1][1]:
h = h + (y - watches[count_+1][1])
y = watches[count_+1][1]
else:
y = y
h = watches[count_+1][3] + (watches[count_+1][1] - y)
count_ += 1
if count_ >= len(watches) - 1:
count_ = len(watches) - 1
patch.append(img_bak[y:y + h, x:x + w])
cv2.rectangle(img, (x-2, y-2), (x + w, y + h), (0, 255, 255), 2)