3、图像处理
图像阈值 thresh
通过对像素点与阈值的比较,当大于阈值或小于阈值时分别进行取值
ret, dst = cv2.threshold(src, thresh, maxval, type)
- src: 输入图,只能输入单通道图像,通常来说为灰度图
- thresh:一般取127和255
- maxval: 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
- type:二值化操作的类型,包含以下5种类型:
- cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
- cv2.THRESH_BINARY_INV THRESH_BINARY的反转
- cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变
- cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
- cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转
- return返回值
- dst: 输出图
- thresh: 阈值
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('cat.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,img_bi = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
ret,img_bi_inv = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY_INV)
ret,img_tr = cv2.threshold(img_gray,127,255,cv2.THRESH_TRUNC)
ret,img_zero = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO)
ret,img_zero_inv = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO_INV)
titles = ['Original','Binary','Binary_INV','TRUNC','ZERO','ZERO_INV']
images = [img,img_bi,img_bi_inv,img_tr,img_zero,img_zero_inv]
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()
图像滤波(平滑)
- cv2.blur # 均值滤波:简单的平均卷积操作
- cv2.boxFilter # 方框滤波:基本和均值一样,可以选择归一化
- cv2.GaussianBlur # 高斯滤波:高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的
- cv2.medianBlur # 中值滤波:相当于用中值代替
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('lenaNoise.png')
# 均值滤波
# 简单的平均卷积操作
blur = cv2.blur(img,(3,3))
# 方框滤波
# 基本和均值一样,可以选择归一化,-1表示通道一致,normalize为真则与均值滤波一样
box = cv2.boxFilter(img,-1,(3,3), normalize=True)
boxFilter = cv2.boxFilter(img,-1,(3,3),normalize=False)
# 高斯滤波
# 高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的
gussian = cv2.GaussianBlur(img,(3,3),1)
# 中值滤波
# 相当于用中值代替
median = cv2.medianBlur(img,5)
titles = ['Original','Binary','Binary_INV','TRUNC','ZERO','ZERO_INV']
images = [img,blur,boxFilter,gussian,median]
# 显示1
# for i in range(5):
# plt.subplot(1,5,i+1),plt.imshow(images[i],'gray'),plt.title(titles[i])
# plt.xticks([]),plt.yticks([]) # 不显示坐标轴
# plt.show()
# 显示2
res = np.hstack((blur,gussian,median))
cv2.imshow('median vs average', res)
cv2.waitKey(0)
cv2.destroyAllWindows()