python - 应用 Horizo​​ntal Sobel Mask 将图像旋转 180 度

标签 python image image-processing edge-detection sobel

在我的一个个人项目中,我尝试在灰度图像上应用以下水平边缘蒙版。通过应用水平边缘掩模,我试图检测图像中的水平边缘。

[1 2 1
 0 0 0 
-1 -2 -1]

当我尝试将图像矩阵与上面给出的掩模进行卷积时,输出图像旋转了 180 度。我不确定这是预期的行为还是我做错了什么?

这是卷积的代码片段。

def convolution(self):
    result = np.zeros((self.mat_width, self.mat_height))
    print(self.mat_width)
    print(self.mat_height)

    for i in range(0, self.mat_width-self.window_width):
        for j in range(0, self.mat_height-self.window_height):
            # deflate both mat and mask 
            # if j+self.window_height >= self.mat_height:
            #   row_index = j+self.window_height + 1
            # else:

            row_index = j+self.window_height                
            col_index = i+self.window_width 

            mat_masked = self.mat[j:row_index, i:col_index]
            # pixel position 
            index_i = i + int(self.window_width / 2) 
            index_j = j + int(self.window_height / 2) 


            prod = np.sum(mat_masked*self.mask)


            if prod >= 255:
                result[index_i, index_j] = 255
            else:
                result[index_i, index_j] = 0

    return result

原始灰度输入图像在这里 - enter image description here

这是正在生成的输出。

enter image description here

最佳答案

写入输出时的索引是相反的。您正在翻转水平和垂直坐标,这实际上会转置图像输出,并且您看到的输出是转置图像的结果。

此外,您没有正确声明图像的输出大小。第一个维度跨越高度,而第二个维度跨越宽度。您必须进行的第一个更改是交换输出图像的输入尺寸:

result = np.zeros((self.mat_height, self.mat_width))

其次,变量index_i是水平遍历,而变量index_j是垂直遍历。您只需翻转顺序即可正确写入结果:

        if prod >= 255:
            result[index_j, index_i] = 255
        else:
            result[index_j, index_i] = 0
<小时/>

如果由于某种原因您不想更改顺序,请保持代码不变,包括如何声明图像的输出尺寸并简单地返回转置后的结果:

return result.T

关于python - 应用 Horizo​​ntal Sobel Mask 将图像旋转 180 度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41268168/

相关文章:

python - QListView 中的自定义项

jquery - 整页背景图像可调整大小 - 保持纵横比

java - 如何从底部开始循环遍历图像中的所有像素?

c++ - 在opencv中使用pow将每个数组元素提升为电源生成错误

python - Tensorflow:是否可以使用不同的火车输入大小和测试输入大小?

python - 具有 NUMERIC 数据类型的 pandas to_sql()

python - 使用 Python 在 Appengine 中解析 xml 的最佳方法

javascript - 如何判断图像是否已使用 Javascript (jQuery) 指定了特定的宽度/高度?

image - 尝试访问位置向量时索引超出矩阵维度

matlab - matlab中的图像标记和寻找质心