任务所需的基本工具/价值是:
- 一种连通分量标注方法;
- 确定是否丢弃或保留连接组件的阈值;
- 用于计算连接组件之间距离的度量标准和用于确定是否加入它们的阈值(仅当您确实想要这样做时才需要这样做,目前还不清楚)。
第一个在 上不可用PIL
,但scipy
提供。如果您也不想使用,请考虑https://stackoverflow.com/a/14350691/1832154scipy
上的答案。我在那个答案中使用了代码,将其调整为使用图像而不是普通列表,并假设那里存在的函数放置在一个名为. 第三步,我以一种时尚的方式使用了简单的棋盘距离。PIL
wu_ccl
O(n^2)
然后,丢弃小于 200 像素的组件,考虑到小于 100 像素的组件应该在同一个边界框中,并将边界框填充 10 像素,这就是我们得到的:
您可以简单地将组件阈值更改为更高的值,以便仅保留最大的值。此外,您可以按相反的顺序执行此图像之前提到的两个步骤:首先加入关闭组件,然后丢弃(但这在下面的代码中没有完成)。
虽然这些是相对简单的任务,但代码并不是那么短,因为我们不依赖任何库来完成这些任务。下面是一个实现上图的示例代码,连接组件的合并特别大,我估计匆忙写出来的代码比需要的要大得多。
import sys
from collections import defaultdict
from PIL import Image, ImageDraw
from wu_ccl import scan, flatten_label
def borders(img):
result = img.copy()
res = result.load()
im = img.load()
width, height = img.size
for x in xrange(1, width - 1):
for y in xrange(1, height - 1):
if not im[x, y]: continue
if im[x, y-1] and im[x, y+1] and im[x-1, y] and im[x+1, y]:
res[x, y] = 0
return result
def do_wu_ccl(img):
label, p = scan(img)
ncc = flatten_label(p)
# Relabel.
l = label.load()
for x in xrange(width):
for y in xrange(height):
if l[x, y]:
l[x, y] = p[l[x, y]]
return label, ncc
def calc_dist(a, b):
dist = float('inf')
for p1 in a:
for p2 in b:
p1p2_chessboard = max(abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
if p1p2_chessboard < dist:
dist = p1p2_chessboard
return dist
img = Image.open(sys.argv[1]).convert('RGB')
width, height = img.size
# Pad image.
img_padded = Image.new('L', (width + 2, height + 2), 0)
width, height = img_padded.size
# "discard" jpeg artifacts.
img_padded.paste(img.convert('L').point(lambda x: 255 if x > 30 else 0), (1, 1))
# Label the connected components.
label, ncc = do_wu_ccl(img_padded)
# Count number of pixels in each component and discard those too small.
minsize = 200
cc_size = defaultdict(int)
l = label.load()
for x in xrange(width):
for y in xrange(height):
cc_size[l[x, y]] += 1
cc_filtered = dict((k, v) for k, v in cc_size.items() if k > 0 and v > minsize)
# Consider only the borders of the remaining components.
result = Image.new('L', img.size)
res = result.load()
im = img_padded.load()
l = label.load()
for x in xrange(1, width - 1):
for y in xrange(1, height - 1):
if im[x, y] and l[x, y] in cc_filtered:
res[x-1, y-1] = l[x, y]
result = borders(result)
width, height = result.size
result.save(sys.argv[2])
# Collect the border points for each of the remainig components.
res = result.load()
cc_points = defaultdict(list)
for x in xrange(width):
for y in xrange(height):
if res[x, y]:
cc_points[res[x, y]].append((x, y))
cc_points_l = list(cc_points.items())
# Perform a dummy O(n^2) method to determine whether two components are close.
grouped_cc = defaultdict(set)
dist_threshold = 100 # pixels
for i in xrange(len(cc_points_l)):
ki = cc_points_l[i][0]
grouped_cc[ki].add(ki)
for j in xrange(i + 1, len(cc_points_l)):
vi = cc_points_l[i][1]
vj = cc_points_l[j][1]
kj = cc_points_l[j][0]
dist = calc_dist(vi, vj)
if dist < dist_threshold:
grouped_cc[ki].add(kj)
grouped_cc[kj].add(ki)
# Flatten groups.
flat_groups = defaultdict(set)
used = set()
for group, v in grouped_cc.items():
work = set(v)
if group in used:
continue
while work:
gi = work.pop()
if gi in flat_groups[group] or gi in used:
continue
used.add(gi)
flat_groups[group].add(gi)
new = grouped_cc[gi]
if not flat_groups[group].issuperset(new):
work.update(new)
# Draw a bounding box around each group.
draw = ImageDraw.Draw(img)
bpad = 10
for cc in flat_groups.values():
data = []
for vi in cc:
data.extend(cc_points[vi])
xsort = sorted(data)
ysort = sorted(data, key=lambda x: x[1])
# Padded bounding box.
bbox = (xsort[0][0] - bpad, ysort[0][1] - bpad,
xsort[-1][0] + bpad, ysort[-1][1] + bpad)
draw.rectangle(bbox, outline=(0, 255, 0))
img.save(sys.argv[2])
同样,wu_ccl.scan
需要调整函数(取自上述答案),为此考虑创建一个带有模式的图像,'I'
而不是使用嵌套的 Python 列表。我还做了一些细微的更改,flatten_label
因此它返回了连接组件的数量(但它实际上并未在呈现的最终代码中使用)。