import skimage.data
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import selectivesearch
def main():
#加载航天员图片
img = skimage.data.astronaut()
#执行选择搜索
img_lbl, regions = selectivesearch.selective_search(
img, scale=500, sigma=0.9, min_size=10)
#创建候选区
candidates = set()
for r in regions:
# 剔除相同矩形 (保留不同矩形)
if r['rect'] in candidates:
continue
# 剔除像素点小于2000的选区
if r['size'] < 2000:
continue
# 剔除长宽比例不符的选区
x, y, w, h = r['rect']
if w / h > 1.2 or h / w > 1.2:
continue
candidates.add(r['rect'])
# 在原始图像上画矩形
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(img)
for x, y, w, h in candidates:
print(x, y, w, h)
rect = mpatches.Rectangle(
(x, y), w, h, fill=False, edgecolor='red', linewidth=1)
ax.add_patch(rect)
plt.show()
if __name__ == "__main__":
main()
结果:
152 17 147 171
46 0 353 326
366 223 93 81
365 345 129 109
364 345 130 109
32 210 207 213
134 348 77 75
255 216 256 295
32 210 207 228
0 210 356 301
42 210 197 213
46 0 353 351
0 0 511 511
111 150 194 198
134 348 75 75
265 216 246 295