证明卷积对翻译是等变的

2024-04-19 23:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了下面的关于卷积和翻译之间的等价关系的声明。在

Let g be a function mapping one image function to another image function, such that I'=g(I) is the image function with I'(x, y) =I(x−1, y). This shifts every pixel ofIone unit to the right. If we apply this transformation to I, then apply convolution, the result will be the same as if we applied convolution to I', then applied the transformation g to the output.

对于我加粗的最后一行,他们将卷积应用于I',但这不应该是I我是翻译的图像。否则,它实际上是在说:

f(g(I)) = g( f(g(I)) )

其中f是卷积,g是翻译。 我正在尝试在python中使用与图像深度相等的3D内核来执行相同的操作,就像在彩色图像的卷积层中一样。在

Input colored image

下面是我对图像应用转换和卷积的代码。在

^{pr2}$

我得到以下输出:

Translated then Convolved

现在,我切换卷积和转换步骤:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import scipy
import scipy.ndimage

I = scipy.ndimage.imread('pics/house.jpg')

def convolution(A, B):
    return np.sum( np.multiply(A, B) )

k = np.array([[[0,1,-1],[1,-1,0],[0,0,0]], [[-1,0,-1],[1,-1,0],[1,0,0]], [[1,-1,0],[1,0,1],[-1,0,1]]]) #kernel


## Convolution
conv = np.zeros( (int((I.shape[0]-3)/2), int((I.shape[1]-3)/2) ) )

for i in range( conv.shape[0] ):
    for j in range(conv.shape[1]):
        conv[i, j] = convolution(I[2*i:2*i+3, 2*j:2*j+3, :], k)


## Translation
translated = 100
new_I = np.zeros( (conv.shape[0]-translated, conv.shape[1]) )

for i in range(translated, conv.shape[0]):
    for j in range(conv.shape[1]):
        new_I[i-translated,j] = conv[i,j]


scipy.misc.imsave('pics/conv_trans_image.png', new_I)

现在我得到以下输出:

First Convolved with kernel & then translated

书上说的不应该是一样的吗?我做错什么了?在


Tags: thetoinimageimportforasnp
1条回答
网友
1楼 · 发布于 2024-04-19 23:22:00

正如书中所说,卷积和平移的线性特性保证了它们的阶数是可以互换的,除了边界效应。在

例如:

import numpy as np
from scipy import misc, ndimage, signal

def translate(img, dx):
    img_t = np.zeros_like(img)
    if dx == 0:  img_t[:, :]   = img[:, :]
    elif dx > 0: img_t[:, dx:] = img[:, :-dx]
    else:        img_t[:, :dx] = img[:, -dx:]
    return img_t

def convolution(img, k):
    return np.sum([signal.convolve2d(img[:, :, c], k[:, :, c])
        for c in range(img.shape[2])], axis=0)

img = ndimage.imread('house.jpg')

k = np.array([
    [[ 0,  1, -1], [1, -1, 0], [ 0, 0, 0]],
    [[-1,  0, -1], [1, -1, 0], [ 1, 0, 0]],
    [[ 1, -1,  0], [1,  0, 1], [-1, 0, 1]]])

ct = translate(convolution(img, k), 100)
tc = convolution(translate(img, 100), k)

misc.imsave('conv_then_trans.png', ct)
misc.imsave('trans_then_conv.png', tc)

if np.all(ct[2:-2, 2:-2] == tc[2:-2, 2:-2]):
    print('Equal!')

印刷品:

Equal!


问题是你在第二个例子中过度翻译了。缩小图像2x后,尝试用50进行翻译。在

相关问题 更多 >