具体的原理:请参考:https://www.jianshu.com/p/b453c0f24b29
参考2:https://yq.aliyun.com/articles/852
import numpy as np
import cv2
import matplotlib.pyplot as plt
#图像阈值处理
img = cv2.imread('../image/dog_1.jpg')
img_gray = cv2.imread('../image/dog_1.jpg',cv2.IMREAD_GRAYSCALE)
"""
输入图像通常为灰度图像
阈值和最大值自己给定,当像素超过阈值或者小于阈值
type:二值化操作的类型,这个是重点记忆理解的
"""
#超过阈值部分取最大值,否则为0
ret,thresh1 = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
#thresh_binary的反转
ret,thresh2 = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY_INV)
#大于阈值部分设置为阈值,否则不变
ret,thresh3 = cv2.threshold(img_gray,127,255,cv2.THRESH_TRUNC)
#大于阈值部分不变,否则为0
ret,thresh4 = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO)
#thresh_tozero的反转
ret,thresh5 = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO_INV)
titles = ['original','binaray','binaray_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()
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('../image/car_10.jpg',cv2.IMREAD_GRAYSCALE)
# cv2.imshow('img',img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
"""
均值滤波
类似于卷积操作
设置卷积核的大小然后对像素点求平均值即可
"""
blur = cv2.blur(img,(3,3))
# cv2.imshow('blur',blur)
# cv2.imwrite('../image/blur_car_10.png',blur)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
"""
方框滤波
和均值一样,可以选择归一化
"""
box = cv2.boxFilter(img,-1,(3,3),normalize=False)
# cv2.imshow('box',box)
# cv2.imwrite('../image/box_car_10.png',box)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
"""
高斯滤波
高斯模糊的卷积核里的数值满足高斯分布,更重视中间的值
"""
gassian = cv2.GaussianBlur(img,(5,5),1)
# cv2.imshow('gassian',gassian)
# cv2.imwrite('../image/gassian_car_10.png',gassian)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
"""
中值滤波
相当于用中值代替
"""
median = cv2.medianBlur(img,5)
# cv2.imshow('median',median)
# cv2.imwrite('../image/median_car_10.png',median)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
"""
显示所有图像
"""
res = np.hstack((blur,gassian,median,box))
cv2.imshow('res',res)
cv2.imwrite('../image/allimage_stack.png',res)
cv2.waitKey()
cv2.destroyAllWindows()