Python-OpenCV中的cv2.threshold


  主要记录Python-OpenCV中的cv2,threshold()方法;官方文档


cv2.threshold()

def threshold(src, thresh, maxval, type, dst=None):
"""
设置固定级别的阈值应用于多通道矩阵
	例如,将灰度图像变换二值图像,或去除指定级别的噪声,或过滤掉过小或者过大的像素点;
Argument:
	src: 原图像
	dst: 目标图像
	thresh: 阈值
	type: 指定阈值类型;下面会列出具体类型;
	maxval: 当type指定为THRESH_BINARY或THRESH_BINARY_INV时,需要设置该值;
"""

  其中type的类型设置入下:

示例:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Time    : 19-4-20 下午5:07
# @Author  : chen

import cv2
import matplotlib.pyplot as plt

lena_BGR = cv2.imread("./input_01.png")
lena_RGB = cv2.cvtColor(lena_BGR, cv2.COLOR_BGR2RGB)

# display BGR lena
plt.subplot(1, 3, 1)
plt.imshow(lena_BGR)
plt.axis('off')
plt.title('img_BGR')

# display RGB lena
plt.subplot(1, 3, 2)
plt.imshow(lena_RGB)
plt.axis('off')
plt.title('img_RGB')

# 转换成灰度图像,并执行高斯模糊
gray = cv2.cvtColor(lena_RGB, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5,5), 0)

# 将图像中小于60的置为0,大于60的置为255
# 返回的temp是一个元组,temp[0]表示设置的阈值,也就是60; temp[1]是变换后的图像
temp = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)
thresh = temp[0]
lena_thresh = temp[1]


# display lena_thresh image
plt.subplot(1, 3, 3)
plt.imshow(lena_thresh, cmap='gray')
plt.axis('off')
plt.title('img_thresh')

plt.show()

posted @ 2019-04-20 20:29  chenzhen0530  阅读(13114)  评论(0编辑  收藏  举报