import cv2
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
src: 输入图,只能输入单通道图像,通常来说为灰度图
dst: 输出图
thresh: 阈值
maxval: 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
type:二值化操作的类型,包含以下5种类型: cv2.THRESH_BINARY; cv2.THRESH_BINARY_INV; cv2.THRESH_TRUNC; cv2.THRESH_TOZERO;cv2.THRESH_TOZERO_INV
cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
cv2.THRESH_BINARY_INV THRESH_BINARY的反转
cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变
cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转
def cvshow(name, ndarray):
# 第一个参数表示显示窗口的名字,第二个参数表示数据
cv2.imshow(name, ndarray)
# 表示等待多久窗口关闭,毫秒单位。0表示按任意键结束
cv2.waitKey(0)
cv2.destroyAllWindows()
boom = cv2.imread("boom.jpg", cv2.IMREAD_GRAYSCALE)
cvshow("boom", boom)
boom.shape
(800, 1280)
# 二值化处理的结果就是黑白图
ret, dst_binary = cv2.threshold(boom, 127, 255, type=cv2.THRESH_BINARY)
ret, dst_binary_inv = cv2.threshold(boom, 127, 255, type=cv2.THRESH_BINARY_INV)
cvshow("binary", dst_binary)
cvshow("binary_inv", dst_binary_inv)
ret, dst_trunc = cv2.threshold(boom, 50, 255, type=cv2.THRESH_TRUNC)
cvshow("trunc", dst_trunc)
ret, dst_tozero = cv2.threshold(boom, 100, 255, type=cv2.THRESH_TOZERO)
cvshow("tozero", dst_tozero)
girl = cv2.imread("girl.jpg")
cvshow("girl", girl)
girl.shape
(333, 500, 3)
blur = cv2.blur(girl, (3, 3))
cvshow("blur", blur)
gau = cv2.GaussianBlur(girl, (3, 3), 1)
cvshow("gau", gau)
median = cv2.medianBlur(girl, 5)
cvshow("median", median)
将所有的处理结果都一起展示
res = np.hstack((blur, gau, median))
cvshow("res", res)