【问题标题】:Why is Python automatically removing negative values from image array?为什么 Python 会自动从图像数组中删除负值?
【发布时间】:2020-03-25 20:19:14
【问题描述】:

我正在尝试在摄影师图像上应用下面的卷积方法。应用于图像的内核是一个填充了 -1/9 的 3x3 过滤器。我在应用 convolve 方法之前打印了摄影师图像的值,我得到的都是正值。接下来,当我在图像上应用 3x3 负核时,当我打印卷积后的摄影师图像的值时,我仍然得到正值。

卷积函数:

def convolve2d(image, kernel):
    # This function which takes an image and a kernel 
    # and returns the convolution of them
    # Args:
    #   image: a numpy array of size [image_height, image_width].
    #   kernel: a numpy array of size [kernel_height, kernel_width].
    # Returns:
    #   a numpy array of size [image_height, image_width] (convolution output).


    output = np.zeros_like(image)            # convolution output
    # Add zero padding to the input image
    padding = int(len(kernel)/2)
    image_padded=np.pad(image,((padding,padding),(padding,padding)),'constant')
    for x in range(image.shape[1]):     # Loop over every pixel of the image
        for y in range(image.shape[0]):
            # element-wise multiplication of the kernel and the image
            output[y,x]=(kernel*image_padded[y:y+3,x:x+3]).sum()        
    return output

这是我对图像应用的过滤器:

filter2= [[-1/9,-1/9,-1/9],[-1/9,-1/9,-1/9],[-1/9,-1/9,-1/9]]

最后,这些是图像的初始值,以及卷积后的值:

[[156 159 158 ... 151 152 152]
 [160 154 157 ... 154 155 153]
 [156 159 158 ... 151 152 152]
 ...
 [114 132 123 ... 135 137 114]
 [121 126 130 ... 133 130 113]
 [121 126 130 ... 133 130 113]]

卷积后:

[[187 152 152 ... 154 155 188]
 [152  99  99 ... 104 104 155]
 [152  99 100 ... 103 103 154]
 ...
 [175 133 131 ... 127 130 174]
 [174 132 124 ... 125 130 175]
 [202 173 164 ... 172 173 202]]

这就是我调用 convolve2d 方法的方式:

convolved_camManImage= convolve2d(camManImage,filter2)

【问题讨论】:

  • 您的图像阵列是什么类型的?可以不签名吗?
  • 在 pad 的 numpy 文档中,我没有看到负值。我怀疑在幕后某处有一个未签名的容器。
  • 我正在使用 numpy 数组:np.array(image)

标签: python numpy image-processing convolution


【解决方案1】:

这可能是由numpydtypes 的工作方式引起的。正如numpy.zeros_like 的帮助所说:

返回与给定形状和类型相同的零数组 数组。

因此,您的 output 可能是 dtype uint8,它使用模运算。要检查是否是这种情况,请在 output = np.zeros_like(image) 行之后立即添加 print(output.dtype)

【讨论】:

  • 我可以改用np.zeros()吗?
  • 好吧,使用 output = np.zeros((image.shape[0],image.shape[1])) 代替 output = np.zeros_like(image) 为我工作!谢谢!
  • 我很高兴为您提供帮助,但要注意output = np.zeros((image.shape[0],image.shape[1])) 可能会被更简洁的行替换:output = np.zeros(image.shape[:2])
猜你喜欢
  • 1970-01-01
  • 2016-02-09
  • 2018-05-24
  • 2017-11-13
  • 1970-01-01
  • 2014-05-30
  • 2020-12-29
  • 2013-09-27
  • 1970-01-01
相关资源
最近更新 更多