图像中棘手的填充孔
Tricky filling holes in an image
我需要使用 python 填充图像中的空洞。
这是我设法得到的带有对象的图像——它们实际上是我想要的对象的边缘,所以我需要填充它们。
使用ndimage.binary_fill_holes(A)
似乎很简单,但问题是它产生了这个(手动填充红色):
但我需要这个:
有什么办法可以解决这个问题吗?
如果您想尝试一下,这是第一张没有轴的图像:
我想我找到了解决办法。由于我 运行 没时间,它有点冗长,但也许它有帮助。我已经为这个问题编写了 if 代码,但是应该很容易将它推广到许多图像。
首先是一些命名约定:
- 我将"first level regions"定义为由背景包围的紧凑区域。这样的一级区域可能由不同的子区域组成。
- 由多个子区域组成的第一级区域称为临界区域。
我的基本想法是比较属于一个关键区域的两个子区域的轮廓长度。不过,我不比较它们的完整轮廓长度,只比较接近背景的部分。靠近背景的轮廓线段较短的被认为是一个洞。
我先从结果图像开始。
对我们正在谈论的内容的一些概述,将上面的命名约定可视化:
临界区的两个子区域。靠近背景的每个区域的两个边界部分用不同的颜色标记(非常细,蓝色和深红色,但可见)。这些段显然并不完美("thin" 区域导致错误),但足以比较它们的长度:
最终结果。如果你想要洞"closed",请告诉我,你只需将原始黑色轮廓分配给区域而不是背景([编辑]我已经包含了三行标记的代码,分配各地区的边界,如您所愿):
这里附上代码。我使用了非常简单的 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()
我需要使用 python 填充图像中的空洞。
这是我设法得到的带有对象的图像——它们实际上是我想要的对象的边缘,所以我需要填充它们。
使用ndimage.binary_fill_holes(A)
似乎很简单,但问题是它产生了这个(手动填充红色):
但我需要这个:
有什么办法可以解决这个问题吗?
如果您想尝试一下,这是第一张没有轴的图像:
我想我找到了解决办法。由于我 运行 没时间,它有点冗长,但也许它有帮助。我已经为这个问题编写了 if 代码,但是应该很容易将它推广到许多图像。
首先是一些命名约定:
- 我将"first level regions"定义为由背景包围的紧凑区域。这样的一级区域可能由不同的子区域组成。
- 由多个子区域组成的第一级区域称为临界区域。
我的基本想法是比较属于一个关键区域的两个子区域的轮廓长度。不过,我不比较它们的完整轮廓长度,只比较接近背景的部分。靠近背景的轮廓线段较短的被认为是一个洞。
我先从结果图像开始。
对我们正在谈论的内容的一些概述,将上面的命名约定可视化:
临界区的两个子区域。靠近背景的每个区域的两个边界部分用不同的颜色标记(非常细,蓝色和深红色,但可见)。这些段显然并不完美("thin" 区域导致错误),但足以比较它们的长度:
最终结果。如果你想要洞"closed",请告诉我,你只需将原始黑色轮廓分配给区域而不是背景([编辑]我已经包含了三行标记的代码,分配各地区的边界,如您所愿):
这里附上代码。我使用了非常简单的 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()