Vel*_*ost 6 python opencv image-processing
我有一张图片.
我想为图像中的每个像素获得3x3窗口(相邻像素).
我有这个Python代码:
for x in range(2,r-1,1):
for y in range(2,c-1,1):
mask5=numpy.array([cv.Get2D(copy_img,x-1,y-1),cv.Get2D(copy_img,x-1,y),cv.Get2D(copy_img,x-1,y+1),cv.Get2D(copy_img,x,y-1),cv.Get2D(copy_img,x,y),cv.Get2D(copy_img,x,y+1),cv.Get2D(copy_img,x+1,y-1),cv.Get2D(copy_img,x+1,y),cv.Get2D(copy_img,x+1,y+1)])
cent=[cv.Get2D(copy_img,x,y)]
Run Code Online (Sandbox Code Playgroud)
mask5是3x3窗口.cent是中心像素.
有没有更有效的方法来做到这一点 - 即使用map,iterators - 除了我使用的两个嵌套循环之外的任何东西?
通过重塑和交换轴,然后重复所有内核元素,可以更快地完成此操作,如下所示:
im = np.arange(81).reshape(9,9)
print np.swapaxes(im.reshape(3,3,3,-1),1,2)
Run Code Online (Sandbox Code Playgroud)
这会给你一个 3*3 的图块数组,这些图块在表面上镶嵌:
[[[[ 0 1 2] [[ 3 4 5] [[ 6 7 8]
[ 9 10 11] [12 13 14] [15 16 17]
[18 19 20]] [21 22 23]] [24 25 26]]]
[[[27 28 29] [[30 31 32] [[33 34 35]
[36 37 38] [39 40 41] [42 43 44]
[45 46 47]] [48 49 50]] [51 52 53]]]
[[[54 55 56] [[57 58 59] [[60 61 62]
[63 64 65] [66 67 68] [69 70 71]
[72 73 74]] [75 76 77]] [78 79 80]]]]
Run Code Online (Sandbox Code Playgroud)
vstack
为了获得重叠的图块,我们需要再重复 8 次,但通过使用和的组合来“包装”数组column_stack
。请注意,右侧和底部的平铺数组环绕(这可能是也可能不是您想要的,具体取决于您如何处理边缘条件):
im = np.vstack((im[1:],im[0]))
im = np.column_stack((im[:,1:],im[:,0]))
print np.swapaxes(im.reshape(3,3,3,-1),1,2)
#Output:
[[[[10 11 12] [[13 14 15] [[16 17 9]
[19 20 21] [22 23 24] [25 26 18]
[28 29 30]] [31 32 33]] [34 35 27]]]
[[[37 38 39] [[40 41 42] [[43 44 36]
[46 47 48] [49 50 51] [52 53 45]
[55 56 57]] [58 59 60]] [61 62 54]]]
[[[64 65 66] [[67 68 69] [[70 71 63]
[73 74 75] [76 77 78] [79 80 72]
[ 1 2 3]] [ 4 5 6]] [ 7 8 0]]]]
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您最终会得到 9 组数组,因此您需要将它们重新压缩在一起。这以及所有的重塑都概括为这一点(对于维度可被 3 整除的数组):
def new(im):
rows,cols = im.shape
final = np.zeros((rows, cols, 3, 3))
for x in (0,1,2):
for y in (0,1,2):
im1 = np.vstack((im[x:],im[:x]))
im1 = np.column_stack((im1[:,y:],im1[:,:y]))
final[x::3,y::3] = np.swapaxes(im1.reshape(rows/3,3,cols/3,-1),1,2)
return final
Run Code Online (Sandbox Code Playgroud)
将此new
函数与循环遍历所有切片(如下)进行比较,timeit
对于 300*300 数组,使用 ,其速度大约快 4 倍。
def old(im):
rows,cols = im.shape
s = []
for x in xrange(1,rows):
for y in xrange(1,cols):
s.append(im[x-1:x+2,y-1:y+2])
return s
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8306 次 |
最近记录: |