对图片进行模糊操作、高斯模糊

    1. import numpy as np
    2. import cv2 as cv
    3. from matplotlib import pyplot as plt
    4. # 2d卷积
    5. def juanji():
    6. img = cv.imread('images/ly.jpg')
    7. image2 = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    8. # 返回一个全1的N维数租 返回取平均值
    9. # 然后替换中心值
    10. # 保持这个内核在一个像素上,将所有低于这个内核的25个像素相加,取其平均值,然后用新的平均值替换中心像素
    11. kernel = np.ones((5, 5), np.float32) / 25
    12. # 当第二个参数为-1 输出图像与原图像有相同的深度
    13. dst = cv.filter2D(image2, -1, kernel)
    14. plt.subplot(121), plt.imshow(image2, "gray"), plt.title('Original')
    15. plt.xticks([]), plt.yticks([])
    16. plt.subplot(122), plt.imshow(dst, "gray"), plt.title('Averaging')
    17. plt.xticks([]), plt.yticks([])
    18. plt.show()
    19. # 平均值
    20. def avg():
    21. img = cv.imread("images/ly.jpg", -1)
    22. # (5,5)是指内核的宽度和高度 获取5/5矩阵内的平均值
    23. blur = cv.blur(img, (5, 5))
    24. plt.subplot(121), plt.imshow(img), plt.title('Original')
    25. plt.xticks([]), plt.yticks([])
    26. plt.subplot(122), plt.imshow(blur), plt.title('Blurred')
    27. plt.xticks([]), plt.yticks([])
    28. plt.show()
    29. # 高斯模糊
    30. def gaosimohu():
    31. images = cv.imread("images/ly.jpg", -1)
    32. # (5,5)是指内核的宽度和高度 获取5/5矩阵内的平均值
    33. # 第一个参数为源地址 第二个参数表示内核的高度跟宽度 必须为正数且奇数
    34. # 第三个参数X和Y的标准偏差 如果指定了x的指那么 y的值也是一样的
    35. img = cv.cvtColor(images, cv.COLOR_BGR2RGB)
    36. blur = cv.GaussianBlur(img, (9, 9), 9)
    37. plt.subplot(121), plt.imshow(img), plt.title('Original')
    38. plt.xticks([]), plt.yticks([])
    39. plt.subplot(122), plt.imshow(blur), plt.title('Blurred')
    40. plt.xticks([]), plt.yticks([])
    41. plt.show()
    42. # 中位模糊
    43. def mediaMohu():
    44. img = cv.imread("images/ly.jpg", -1)
    45. images = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    46. # 5 表示核大小 应为奇数字
    47. # 中位 模糊的意思 按照核大小 排序 取排序后的值替代掉中间点的位置
    48. # 如果核心为3x3 那么就是在这个核当中 3x3 排序 排序完的中间值替换掉以前的中心值
    49. blur = cv.medianBlur(images, 5)
    50. plt.subplot(121), plt.imshow(images)
    51. plt.subplot(122), plt.imshow(blur)
    52. plt.show()
    53. if __name__ == '__main__':
    54. # avg()
    55. # gaosimohu()
    56. mediaMohu()