2020-06-15-image-smooth-show

Record

Posted by Jocelyn on June 15, 2020

2020-06-15-recording.

# -*- coding: UTF-8 -*-
#图像截取 并显示
import cv2
import matplotlib.pylab as plt#注意这里的pylab 如果没有的话,会报错
img=cv2.imread('/Users/syy/learn/repositories/blogPost/JocelynHub.github.io/img/post-sample-image.jpg')
img=img[0:200,0:200]

#显示
# cv2.imshow('test',img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#显示
thesh = 127
maxval=255
ret,thresh1 = cv2.threshold(img,thesh,maxval,cv2.THRESH_BINARY)
#如果>阈值,结果就会是maxval,否则就是0
ret,thresh2 = cv2.threshold(img,thesh,maxval,cv2.THRESH_BINARY_INV)
#如果>阈值,结果就会是0,否则就是maxval
ret,thresh3 = cv2.threshold(img,thesh,maxval,cv2.THRESH_TRUNC)
#如果>阈值,结果就会是maxval,否则dst = src
ret,thresh4 = cv2.threshold(img,thesh,maxval,cv2.THRESH_TOZERO)
#如果>阈值,dst = src,否则就是0
ret,thresh5 = cv2.threshold(img,thesh,maxval,cv2.THRESH_TOZERO_INV)
#如果>阈值,dst = 0,否则就是dst = src
titles = ['Original','Binary','Binary_inv','Trunc','Tozero','Tozero_inv']
images = [img,thresh1,thresh2,thresh3,thresh4,thresh5]

for i in range(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
#plt.show()

#图像平滑
#均值滤波
blur = cv2.blur(img,(3,3))

#方框滤波
box = cv2.boxFilter(img,-1,(3,3),normalize=True)
#-1,表示输入和输出在颜色通道上是一致的
#如果不做normalize,容易越界,越界后为255

#高斯滤波
sigma=1
gaussian = cv2.GaussianBlur(img,(5,5),sigma)

#中值滤波
median = cv2.medianBlur(img,5)

#展示所有结果的方式
import numpy as np
#resH = np.hstack(blur,gaussian,median)#这里因为少个括号,会有问题
resH = np.hstack((blur,gaussian,median))
cv2.imshow('hstack',resH)
# cv2.waitKey(0)
resV = np.vstack((blur,gaussian,median))
cv2.imshow('vstack',resV)
# cv2.waitKey(0)