一、图像阈值操作
ret, dst = cv2.threshold(src, thresh, maxval, type)
src:输入图,只能输入单通道图,通常来说为灰度图
dst:输出图
thresh:阈值
maxval:当像素超过了阈值(或小于阈值,由type决定),所赋予的值
type:二值化操作的类型,包含以下五种:
### cv2.THRESH_BINARY 超过阈值部分取maxval,否则取0
### cv2.THRESH_BINAEY_INV 超过阈值部分取0,否则取maxval
### cv2.THRESH_TRUNC 大于阈值部分设为maxval,否则不变
### cv2.THRESH_TOZERO 大于阈值部分不改变,否则为0
### cv2.THRESH_TOZERO_INV 大于阈值部分设为0,否则不改变
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('./cat.jpg', cv2.IMREAD_GRAYSCALE)
ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
plt.figure()
plt.subplot(2, 3, 1)
plt.imshow(img, 'gray')
plt.title('ORIGINAL')
plt.subplot(2, 3, 2)
plt.imshow(thresh1, 'gray')
plt.title('BINARY')
plt.subplot(2, 3, 3)
plt.imshow(thresh2, 'gray')
plt.title('BIANRY_INV')
plt.subplot(2, 3, 4)
plt.imshow(thresh3, 'gray')
plt.title('TRUNC')
plt.subplot(2, 3, 5)
plt.imshow(thresh4, 'gray')
plt.title('TOZERO')
plt.subplot(2, 3, 6)
plt.imshow(thresh5, 'gray')
plt.title('TOZERO_INV')
plt.show()
二、图像平滑处理
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('./noisy.jpg', cv2.IMREAD_COLOR)
b, g, r = cv2.split(img)
img = cv2.merge((r, g, b))
plt.figure()
plt.subplot(2, 3, 1)
plt.imshow(img, 'gray')
plt.title('ORIGINAL')
#均值滤波
#简单的平均卷积操作
blur = cv2.blur(img, (3, 3))
plt.subplot(2, 3, 2)
plt.imshow(blur, 'gray')
plt.title('BLUR')
#方框滤波
#基本和均值一样,可以选择归一化
box = cv2.boxFilter(img, -1, (3, 3), normalize=True)
plt.subplot(2, 3, 3)
plt.imshow(box, 'gray')
plt.title('BOX_NORMALIZE')
#方框滤波
#不做归一化会越界。越界全部按255处理
box = cv2.boxFilter(img, -1, (3, 3), normalize=False)
plt.subplot(2, 3, 4)
plt.imshow(box, 'gray')
plt.title('BOX_NONE')
#高斯滤波
#高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的
gaussian = cv2.GaussianBlur(img, (5, 5), 1)
plt.subplot(2, 3, 5)
plt.imshow(gaussian, 'gray')
plt.title('GAUSSIAN')
#中值滤波
#相当于用中值代替
median = cv2.medianBlur(img, 5)
plt.subplot(2, 3, 6)
plt.imshow(median, 'gray')
plt.title('MEDIAN')
plt.show()