Python 一种快速移除接近像素的方法
我有一个粗线像素的图像,它下面有一条线。我想Python 一种快速移除接近像素的方法,python,numpy,Python,Numpy,我有一个粗线像素的图像,它下面有一条线。我想 删除底线 把粗线减薄 所以我使用了这个循环: N = 1000 im = (np.random.random((N, N)) - 0.5) xx,yy = np.where(im > 0) for x,y in zip(xx,yy): for i in range(xmin,xmax): # I played with the limits so they would fit my specific image #
N = 1000
im = (np.random.random((N, N)) - 0.5)
xx,yy = np.where(im > 0)
for x,y in zip(xx,yy):
for i in range(xmin,xmax): # I played with the limits so they would fit my specific image
# if inner loop already broke
if im[x][y] == False:
break
for j in range(ymin,ymax): # here again
if im[x-i][y+j]:
im[x][y] = False
break
这对(~95%不需要的像素被移除)非常有效,但速度非常慢。。。每个图像大约需要1秒的时间,像np.where,np.argmax
这样的操作需要<0.01秒
如何使用numpy
(我猜numpy
最适合)来加速它
编辑:按照@jmd_dk的建议使用@numba.jit
非常有用,但它似乎仍然比正常的numpy
方法慢
为了澄清,我不仅要找到正像素的位置,如np.where(im>0)
所提供的,而且要找到正像素位于正像素下方/上方的像素位置
如果我有这个矩阵:
0 | 0 | 0 | 1 | 1 | 1 | 0
0 | 0 | 0 | 0 | 0 | 0 | 1
0 | 1 | 0 | 1 | 0 | 1 | 1
0 | 0 | 0 | 1 | 1 | 0 | 1
0 | 0 | 0 | 0 | 0 | 0 | 1
0 | 1 | 0 | 1 | 1 | 1 | 1
0 | 0 | 0 | 1 | 1 | 1 | 0
0 | 0 | 0 | 0 | 0 | 0 | 1
0 | 1 | 0 | * | 0 | * | *
0 | 0 | 0 | * | * | 0 | *
0 | 0 | 0 | 0 | 0 | 0 | *
0 | * | 0 | * | * | * | *
我想找到上面有'1'
的所有'1'
像素,并将其删除-获取此矩阵:
0 | 0 | 0 | 1 | 1 | 1 | 0
0 | 0 | 0 | 0 | 0 | 0 | 1
0 | 1 | 0 | 1 | 0 | 1 | 1
0 | 0 | 0 | 1 | 1 | 0 | 1
0 | 0 | 0 | 0 | 0 | 0 | 1
0 | 1 | 0 | 1 | 1 | 1 | 1
0 | 0 | 0 | 1 | 1 | 1 | 0
0 | 0 | 0 | 0 | 0 | 0 | 1
0 | 1 | 0 | * | 0 | * | *
0 | 0 | 0 | * | * | 0 | *
0 | 0 | 0 | 0 | 0 | 0 | *
0 | * | 0 | * | * | * | *
我用
*
替换了1
,因此它会突出…这是Numba真正闪耀的地方。在没有任何实际工作的情况下,我立即获得约115倍的加速比(倍,而不是百分比!)。我没有你的整个代码,但是考虑这个例子:
import numpy as np
import numba
from time import time
@numba.jit
def fun():
# Added just to make the code run
t0 = time()
N = 1000
im = (np.random.random((N, N)) - 0.5)
xmin = ymin = 0
xmax = ymax = N
# Your code
xx,yy = np.where(im > 0)[0], np.where(im > 0)[1]
for x,y in zip(xx,yy):
for i in range(xmin,xmax):
if im[x][y] == False:
break
for j in range(ymin,ymax):
if im[x-i][y+j]:
im[x][y] = False
break
t1 = time()
print('took', t1 - t0, 's')
fun()
fun()
在我的机器上,我得到
取0.18608522415161133秒
取0.0416417121887207秒
现在移除numba.jit
decorator,我得到
取4.783859491348267秒
拍摄4.796429872512817 s
获取Numba包的最简单方法是使用Python发行版
然后,应该为每个图像调用一次函数(此处为
fun()
)。第一次调用函数时,Numba会将其编译为快速代码,这就是为什么第一次调用比第二次慢得多(尽管仍然比正常的非Numba版本快得多)。不清楚您想要什么。你能提供样本输入和样本输出吗?顺便说一句,xx,yy=np.where(im>0)[0],np.where(im>0)[1]
只是x,yy=np.where(im>0)
@lilisten为了更好的清晰度而编辑的!!37.32秒(无numba
)-->6.94秒(第一次numba
)-->3.21秒(第二次numba
)!!谢谢顺便说一句,使用@jit(cache=True)
将时间进一步缩短一半