我想使用函数cv2.connectedComponents来连接二进制映像上的组件,如下所示...
的数据
我已经把这个特性添加到了cv2。connectedComponents以消除具有少量像素的元素。
不幸的是,该算法是非常缓慢的大图像,由于扩展。有没有办法重写扩展来加速算法?
import cv2
import numpy as np
def zerolistmaker(n):
listofzeros = [0] * n
return listofzeros
img = cv2.imread('files/motorway/gabor/eGaIy.jpg', 0)
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
retval, labels = cv2.connectedComponents(img)
##################################################
# ENLARGEMENT
##################################################
sorted_labels = labels.ravel()
sorted_labels = np.sort(sorted_labels)
maxPixel = 50 # eliminate elements with less than maxPixel
# detect how often an element occurs
i=0
counter=0
counterlist = zerolistmaker(retval)
while i < len(sorted_labels):
if sorted_labels[i] == counter:
counterlist[counter] = counterlist[counter] + 1
else:
counter = counter + 1
i = i - 1
i = i + 1
# delete small pixel values
i=0
while i < len(counterlist):
if counterlist[i] < maxPixel:
counterlist[i] = 0
i = i + 1
i=0
counterlisthelper = []
while i < len(counterlist):
if counterlist[i] == 0:
counterlisthelper.append(i)
i = i + 1
i=0
j=0
k=0
while k < len(counterlisthelper):
while i < labels.shape[0]:
while j < labels.shape[1]:
if labels[i,j] == counterlisthelper[k]:
labels[i,j] = 0
else:
labels[i,j] = labels[i,j]
j = j + 1
j = 0
i = i + 1
i = 0
j = 0
k = k + 1
##################################################
##################################################
# Map component labels to hue val
label_hue = np.uint8(179*labels/np.max(labels))
blank_ch = 255*np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
# set bg label to black
labeled_img[label_hue==0] = 0
cv2.imshow('labeled.png', labeled_img)
cv2.waitKey()
字符串
2条答案
按热度按时间iqjalb3h1#
在Python中,你应该避免深度循环。使用
numpy
而不是python-loop
。改进:
字符串
测试结果:
100d1x
的字符串
整个代码:
型
ttp71kqs2#
我知道我已经很晚了,但我发现了一个解决方案,它比
Kinght 金
的解决方案快两倍多。此解决方案在我的计算机上运行600×800图像的时间约为350ms,而其他解决方案的时间约为850ms。功能:
字符串
支持代码:
的数据