python - 为什么 Python 会自动从图像数组中删除负值?
问题描述
我正在尝试在摄影师图像上应用下面的卷积方法。应用于图像的内核是一个填充了 -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)
解决方案
这可能是由numpy
dtype
s 的工作方式引起的。正如numpy.zeros_like
帮助所说:
返回与给定数组具有相同形状和类型的零数组。
因此,您output
可能是 dtype uint8
,它使用模运算。要检查是否是这种情况,请在行print(output.dtype)
后立即添加output = np.zeros_like(image)
推荐阅读
- node.js - 使用复选框显示禁用的用户
- python - 找不到 Django 静态页面 404
- java - 为什么执行同步方法后线程仍然锁定?
- python - 为什么我使用 gensim LSI 模型得到不同长度的向量?
- spring-boot - Kubernetes网络,如何将变量传递到容器中
- node.js - babel-register 在 mocha 测试中不起作用,nodejs 做出反应
- python - Python如何计算与csv列的相关系数?
- android - 没有在 linux react-native compile exit 编译我的 poyect
- excel - 更新 Power Query 源
- oracle - TypeORM Oracle 驱动程序,适用于 query.raw 但不适用于实体