python - 简单的 Python 模糊卷积核函数生成奇怪的图像
问题描述
我正在编写一个自定义函数来使用卷积核对图像应用模糊。但是,当我显示图像时,会出现奇怪的结果。在某些方面似乎图像是倒置的,但我不知道为什么。这是原始图像:
结果如下:
我已经尝试过重新编写代码,更改图像,更改模糊内核,打印并亲自通过眼睛进行许多卷积等。
import cv2
import numpy as np
import matplotlib.pyplot as plt
def showImage(image):
plt.imshow(image, cmap='gray')
plt.show()
def gaussianBlur(image):
tempImage = image.copy()
tempImage = np.pad(tempImage, 1, "constant")
showImage(tempImage)
max = 0
i = 0
for x in range(1, len(image)-1):
for y in range(1, len(image[0])-1):
roi = image[x-1:x+2, y-1:y+2]
kernel = np.array([
[0.0625, 0.125, 0.0625],
[0.125, 0.25, 0.125],
[0.0625, 0.125, 0.0625]
])
if np.matmul(roi, kernel).sum() > max:
max = np.matmul(roi, kernel).sum()
tempImage[x][y] = np.matmul(roi, kernel).sum()
i += 1
print(np.matmul(roi, kernel).sum())
# if(i % 1000 == 0):
# showImage(tempImage)
divAmount = max / 255
for x in range(1, len(image)-1):
for y in range(1, len(image[0])-1):
tempImage[x][y] = tempImage[x][y] / divAmount
return tempImage.tolist()
# Load and view the image
image = cv2.imread("image_1_small.jpg", 0)
showImage(image)
# Apply Blur
image = gaussianBlur(image)
print(image)
# image = cv2.GaussianBlur(image, (5, 5), 0)
showImage(image)
预期的结果应该看起来像原始图像只是模糊的。
解决方案
这是由溢出引起的。你计算卷积错误。使用 np.multiply 代替 np.matmul。
推荐阅读
- python - 如何使用numpy(首选)或python 3将数组作为单独的列添加到CSV文件而不覆盖CSV文件或数据?
- javascript - How to split a html string with start and end character
- javascript - Center Custom Cursor
- reactjs - Do I have to use the
when I want to use in ReactJs? - amazon-dynamodb - Create rule in AWS IoT core to insert data into an existing row in DynamoDB
- html - I have problems with the tomcat server while trying to run my JPS
- html - Check if variable, function, method is available/set to avoid error
- python - class function Callback is not accessed
- android - How to reference libraries inside an APK, building an Android image
- r - Hiding output of stepAIC in Rmarkdown