我正在尝试实现一种采用两个 vector 的卷积方法:图像;和一个内核。我的问题是,当我将内核“滑动”到图像 vector 上时,我不知道如何计算图像相邻元素的索引。例如,对于两个相同的 vector {0, 1, 2, 3, 4, 5, 6, 7, 8} 我希望获得以下结果:
到目前为止我的代码如下:
public int[] convolve(int[] image, int[] kernel)
{
int imageValue;
int kernelValue;
int outputValue;
int[] outputImage = new int[image.length()];
// loop through image
for(int i = 0; i < image.length(); i++)
{
outputValue = 0;
// loop through kernel
for(int j = 0; j < kernel.length(); j++)
{
neighbour = ?;
// discard out of bound neighbours
if (neighbour >= 0 && neighbour < imageSize)
{
imageValue = image[neighbour];
kernelValue = kernel[j];
outputValue += imageValue * kernelValue;
}
}
output[i] = outputValue;
}
return output;
}
最佳答案
由于 i + j - (kernel.length/2)
对于答案来说可能太短:
public class Convolution
{
public static void main(String[] args)
{
int image[] = { 0,1,2,3,4,5,6,7,8 };
int kernel[] = { 0,1,2,3,4,5,6,7,8 };
int output[] = convolve(image, kernel);
for (int i=0; i<image.length; i++)
{
System.out.printf(output[i]+" ");
}
}
public static int[] convolve(int[] image, int[] kernel)
{
int[] output = new int[image.length];
// loop through image
for(int i = 0; i < image.length; i++)
{
System.out.println("Compute output["+i+"]");
int outputValue = 0;
// loop through kernel
for(int j = 0; j < kernel.length; j++)
{
int neighbour = i + j - (kernel.length / 2);
// discard out of bound neighbours
if (neighbour >= 0 && neighbour < image.length)
{
int imageValue = image[neighbour];
int kernelValue = kernel[j];
outputValue += imageValue * kernelValue;
System.out.println("image["+neighbour+"] and kernel["+j+"]");
}
}
output[i] = outputValue;
}
return output;
}
}
请注意,只有当内核长度为奇数时,此方法才能正常工作。事实上,您所做的是将内核的中心移动到图像空间(这是kernel.length/2
的来源)。对于偶数长度的内核,例如0 1 2 3
,您必须决定是否要包含...
0 1 2 3 4 (image)
3 <- This line and/or ...
2 3
1 2 3
0 1 2 3
0 1 2 3
0 1 2
0 1
0 <- ... this line
关于java - vector 卷积 - 计算相邻元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701089/