Ima*_*ngo 6 python numpy convolution scipy scikit-image
scipy(或其他类似的库)中是否有办法仅在某些所需的点上获取具有给定内核的图像的卷积?
我正在寻找类似的东西:
ndimage.convolve(image, kernel, mask=mask)
Run Code Online (Sandbox Code Playgroud)
其中mask包含True(或1)每当内核需要被应用,False(或0)其他方式。
编辑:示例python代码可以完成我想做的事情(但不比使用scipy进行整个图像卷积要快):
def kernel_responses(im, kernel, mask=None, flatten=True):
if mask is None:
mask = np.ones(im.shape[:2], dtype=np.bool)
ks = kernel.shape[0]//2
data = np.pad(im, ks, mode='reflect')
y, x = np.where(mask)
responses = np.empty(y.shape[0], float)
for k, (i, j) in enumerate(zip(y, x)):
responses[k] = (data[i:i+ks*2+1, j:j+ks*2+1] * kernel).sum()
if flatten:
return responses
result = np.zeros(im.shape[:2], dtype=float)
result[y, x] = responses
return result
Run Code Online (Sandbox Code Playgroud)
上面的代码使用wrap边界条件来完成这项工作,但是内部循环在python中进行,因此很慢。我在想,如果有东西在快已经实施scipy/ opencv/ skimage。
我知道我正在回答自己的答案,希望下面的代码有进一步的改进,否则可能对其他用户有用。
下面的代码是cython / python实现:
蟒蛇:
def py_convolve(im, kernel, points):
ks = kernel.shape[0]//2
data = np.pad(im, ks, mode='constant', constant_values=0)
return cy_convolve(data, kernel, points)
Run Code Online (Sandbox Code Playgroud)
赛扬:
import numpy as np
cimport cython
@cython.boundscheck(False)
def cy_convolve(unsigned char[:, ::1] im, double[:, ::1] kernel, Py_ssize_t[:, ::1] points):
cdef Py_ssize_t i, j, y, x, n, ks = kernel.shape[0]
cdef Py_ssize_t npoints = points.shape[0]
cdef double[::1] responses = np.zeros(npoints, dtype='f8')
for n in range(npoints):
y = points[n, 0]
x = points[n, 1]
for i in range(ks):
for j in range(ks):
responses[n] += im[y+i, x+j] * kernel[i, j]
return np.asarray(responses)
Run Code Online (Sandbox Code Playgroud)
与其他方法的比较
下表显示了4种方法的评估:
每行中,为了对应于这些方法对于3幅不同的图像(coins,camera并lena从skimage.data分别地)和每一列对应于一个不同的ammount的点来计算内核响应的(是百分比为意指“在计算响应x%的点的图片”)。
为了用少于50%点的方式计算内核响应,我的实现比卷积整个图像要快,但反之则不快。
编辑:测试的内核窗口是5x5统一窗口(np.ones((5,5)))。
['303x384'] 1% 2% 5% 10% 20% 50%
1 4.97 9.58 24.32 48.28 100.39 245.77
2 7.60 15.09 37.42 75.17 150.09 375.60
3 3.05 2.99 3.04 2.88 2.96 2.98
4 0.17 0.22 0.38 0.60 1.10 2.49
['512x512'] 1% 2% 5% 10% 20% 50%
1 10.68 21.87 55.47 109.16 223.58 543.73
2 17.90 34.59 86.02 171.20 345.46 858.24
3 6.52 6.53 6.74 6.63 6.43 6.60
4 0.31 0.43 0.78 1.34 2.73 6.82
['512x512'] 1% 2% 5% 10% 20% 50%
1 13.21 21.45 54.98 110.80 217.11 554.96
2 19.55 34.78 87.09 172.33 344.58 893.02
3 6.87 6.82 7.00 6.60 6.64 7.71
4 0.35 0.47 0.87 1.57 2.47 6.07
Run Code Online (Sandbox Code Playgroud)
注意:时间以表示ms。
我不知道有什么功能可以完全满足您的要求。如果您不提供要卷积的点的掩码,而是提供点列表,例如。[(7, 7), (100, 100)]那么它可能就像获取适当的图像补丁(例如与提供的内核大小相同),将图像补丁和内核进行卷积,然后插入回原始图像一样简单。
这是一个编码示例,希望它足够接近以便您可以稍微修改:
[编辑:我注意到我的填充和补丁算术中有几个错误。以前,您无法与边界上的点(例如 (0, 0))进行卷积,我将填充加倍,修复了一些算术,现在一切都很好。]
import cv2
import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt
def image_convolve_mask(image, list_points, kernel):
# list_points ex. [(7, 7), (100, 100)]
# assuming kernels of dims 2n+1 x 2n+1
rows, cols = image.shape
k_rows, k_cols = kernel.shape
r_pad = int(k_rows/2)
c_pad = int(k_cols/2)
# zero-pad the image in case desired point is close to border
padded_image = np.zeros((rows + 2*k_rows, cols + 2*k_cols))
# set the original image in the center
padded_image[k_rows: rows + k_rows, k_cols: cols + k_cols] = image
# should you prefer to use np.pad:
# padded_image = np.pad(image, (k_rows, k_cols), 'constant', constant_values=(0, 0))
for p in list_points:
# extract pertinent patch from image
# arbitrarily choosing the patch as same size as the kernel; change as needed
patch = padded_image[p[0] + k_rows - r_pad: p[0] + 2*k_rows - r_pad, p[1] + k_cols - c_pad: p[1] + 2*k_cols - c_pad]
# here use whatever function for convolution; I prefer cv2filter2D()
# commented out is another option
# conv = ndimage.convolve(patch, kernel, mode='constant', cval=0.0)
conv = cv2.filter2D(patch, -1, kernel)
# set the convolved patch back in to the image
padded_image[p[0] + k_rows - r_pad: p[0] + 2*k_rows - r_pad, p[1] + k_cols - c_pad: p[1] + 2*k_cols - c_pad] = conv
return padded_image[k_rows: rows + k_rows, k_cols: cols + k_cols]
Run Code Online (Sandbox Code Playgroud)
现在在图像上尝试一下:
penguins = cv2.imread('penguins.png', 0)
kernel = np.ones((5,5),np.float32)/25
# kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], np.float32)
conv_image = image_convolve_mask(penguins, [(7, 7), (36, 192), (48, 207)], kernel)
plt.imshow(conv_image, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()
Run Code Online (Sandbox Code Playgroud)
我应用了一个更平滑的 5x5 盒子,实际上看不到像素 (7, 7) 周围的任何变化,但我选择了另外两个点作为最左边两个企鹅喙的尖端。所以你可以看到平滑的补丁。

这是具有 21 个卷积点的 lena512 图像(时间:0.006177 秒)。

[编辑2:使用掩码生成行、列元组列表以馈入函数的示例。]
mask = np.eye(512)
k = np.ones((25, 25), np.float32)/625
list_mask = zip(np.where(mask==1)[0], np.where(mask==1)[1])
tic = time.time()
conv_image = image_convolve_mask(lena, list_mask, k)
print 'time: ', time.time()-tic # 0.08136 sec
Run Code Online (Sandbox Code Playgroud)
