OpenCV图像阈值操作和平滑处理

一、图像阈值操作

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()

cat

二、图像平滑处理

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()

滤波

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值