为什么Python会自动从图像数组中删除负值?

时间:2019-11-30 16:51:16

标签: python numpy image-processing convolution

我正在尝试在摄影师图像上应用以下卷积方法。应用于图像的内核是3x3滤镜,其中填充了-1/9。在应用卷积方法之前,我先打印摄影师图像的值,而我得到的都是正值。接下来,当我在Image上应用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)

1 个答案:

答案 0 :(得分:1)

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

  

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

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

相关问题