我想我已经找到了解决方案。由于我没时间了,所以有点长,但也许有帮助。我只针对这个问题编写了 if 代码,但应该很容易将其推广到许多图像。
首先是一些命名约定:
我的基本想法是比较属于一个关键区域的两个子区域的轮廓长度。但是,我没有比较它们的完整轮廓长度,而是仅比较靠近背景的部分。轮廓线段较短、靠近背景的部分被视为洞。
我首先从结果图像开始。
我们所讨论的内容的一些概述,可视化上面的命名约定:
关键区域的两个子区域。每个区域靠近背景的两个边界段都用不同的颜色标记(很细,蓝色和深红色,但可见)。这些段显然并不完美(“薄”区域会导致错误),但足以比较它们的长度:
最终结果。如果您想让孔“闭合”,请告诉我,您只需将原始黑色轮廓分配给区域而不是背景([编辑]我已经包含了三行标记的代码,它们分配了边框到地区,如您所愿):
代码附在这里。我使用了非常简单的 OpenCV 轮廓函数和一些遮罩技术。该代码由于其可视化而显得冗长,对其可读性有限感到抱歉,但似乎没有两行解决方案可以解决此问题。
最后的一些评论:我首先尝试使用点集进行轮廓匹配,这将避免循环并允许使用 set.intersection 来确定靠近背景的两个轮廓段,但由于你的黑线相当粗,轮廓略有不匹配。我尝试了轮廓的骨架化,但这又带来了麻烦,所以我使用转储方法进行循环并计算轮廓点之间的距离。可能有更好的方法来完成这部分,但它确实有效。
我也考虑过使用Shapely模块,可能有一些方法可以从中获得一些好处,但我没有找到任何方法,所以我又放弃了它。
import numpy as np
import scipy.ndimage as ndimage
from matplotlib import pyplot as plt
import cv2
img= ndimage.imread('image.png')
# Label digfferentz original regions
labels, n_regions = ndimage.label(img)
print "Original number of regions found: ", n_regions
# count the number of pixels in each region
ulabels, sizes = np.unique(labels, return_counts=True)
print sizes
# Delete all regions with size < 2 and relabel
mask_size = sizes < 2
remove_pixel = mask_size[labels]
labels[remove_pixel] = 0
labels, n_regions = ndimage.label(labels) #,s)
print "Number of regions found (region size >1): ", n_regions
# count the number of pixels in each region
ulabels, sizes = np.unique(labels, return_counts=True)
print ulabels
print sizes
# Determine large "first level" regions
first_level_regions=np.where(labels ==1, 0, 1)
labeled_first_level_regions, n_fl_regions = ndimage.label(first_level_regions)
print "Number of first level regions found: ", n_fl_regions
# Plot regions and first level regions
fig = plt.figure()
a=fig.add_subplot(2,3,1)
a.set_title('All regions')
plt.imshow(labels, cmap='Paired', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([]), plt.colorbar()
a=fig.add_subplot(2,3,2)
a.set_title('First level regions')
plt.imshow(labeled_first_level_regions, cmap='Paired', vmin=0, vmax=n_fl_regions)
plt.xticks([]), plt.yticks([]), plt.colorbar()
for region_label in range(1,n_fl_regions):
mask= labeled_first_level_regions!=region_label
result = np.copy(labels)
result[mask]=0
subregions = np.unique(result).tolist()[1:]
print region_label, ": ", subregions
if len(subregions) >1:
print " Element 4 is a critical element: ", region_label
print " Subregions: ", subregions
#Critical first level region
crit_first_level_region=np.ones(labels.shape)
crit_first_level_region[mask]=0
a=fig.add_subplot(2,3,4)
a.set_title('Crit. first level region')
plt.imshow(crit_first_level_region, cmap='Paired', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])
#Critical Region Contour
im = np.array(crit_first_level_region * 255, dtype = np.uint8)
_, contours0, hierarchy = cv2.findContours( im.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
crit_reg_contour = [contours0[0].flatten().tolist()[i:i+2] for i in range(0, len(contours0[0].flatten().tolist()), 2)]
print crit_reg_contour
print len(crit_reg_contour)
#First Subregion
mask2= labels!=subregions[1]
first_subreg=np.ones(labels.shape)
first_subreg[mask2]=0
a=fig.add_subplot(2,3,5)
a.set_title('First subregion: '+str(subregions[0]))
plt.imshow(first_subreg, cmap='Paired', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])
#First Subregion Contour
im = np.array(first_subreg * 255, dtype = np.uint8)
_, contours0, hierarchy = cv2.findContours( im.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
first_sub_contour = [contours0[0].flatten().tolist()[i:i+2] for i in range(0, len(contours0[0].flatten().tolist()), 2)]
print first_sub_contour
print len(first_sub_contour)
#Second Subregion
mask3= labels!=subregions[0]
second_subreg=np.ones(labels.shape)
second_subreg[mask3]=0
a=fig.add_subplot(2,3,6)
a.set_title('Second subregion: '+str(subregions[1]))
plt.imshow(second_subreg, cmap='Paired', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])
#Second Subregion Contour
im = np.array(second_subreg * 255, dtype = np.uint8)
_, contours0, hierarchy = cv2.findContours( im.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
second_sub_contour = [contours0[0].flatten().tolist()[i:i+2] for i in range(0, len(contours0[0].flatten().tolist()), 2)]
print second_sub_contour
print len(second_sub_contour)
maxdist=6
print "Points in first subregion close to first level contour:"
close_1=[]
for p1 in first_sub_contour:
for p2 in crit_reg_contour:
if (abs(p1[0]-p2[0])+abs(p1[1]-p2[1]))<maxdist:
close_1.append(p1)
break
print close_1
print len(close_1)
print "Points in second subregion close to first level contour:"
close_2=[]
for p1 in second_sub_contour:
for p2 in crit_reg_contour:
if (abs(p1[0]-p2[0])+abs(p1[1]-p2[1]))<maxdist:
close_2.append(p1)
break
print close_2
print len(close_2)
for p in close_1:
result[p[1],p[0]]=1
for p in close_2:
result[p[1],p[0]]=2
if len(close_1)>len(close_2):
print "first subregion is considered a hole:", subregions[0]
hole=subregions[0]
else:
print "second subregion is considered a hole:", subregions[1]
hole=subregions[1]
#Plot Critical region with subregions
a=fig.add_subplot(2,3,3)
a.set_title('Critical first level region with subregions')
plt.imshow(result, cmap='Paired', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])
result2=result.copy()
#Plot result
fig2 = plt.figure()
a=fig2.add_subplot(1,1,1)
a.set_title('Critical first level region with subregions and bordering contour segments')
plt.imshow(result2, cmap='flag', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])
#Plot result
mask_hole=np.where(labels ==hole, True, False)
labels[mask_hole]=1
labels=np.where(labels > 1, 2, 1)
# [Edit] Next two lines include black borders into final result
mask_borders=np.where(img ==0, True, False)
labels[mask_borders]=2
fig3 = plt.figure()
a=fig3.add_subplot(1,1,1)
a.set_title('Final result')
plt.imshow(labels, cmap='flag', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
955 次 |
| 最近记录: |