python opencv 图片阈值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/TingHW/article/details/84526671
# 简单阈值
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('black_white.jpg', 0)
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)

titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]

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

在这里插入图片描述

# 下面的代码比较了全局阈值和适应性阈值在处理一个变化光线的图片的差别
# 自适应二值化,用于解决图片中明暗不均导致阈值设置不能有效分割图像。

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('black_white2.jpg',0)
img = cv2.medianBlur(img,5)#第一个参数是待处理图像,第二个参数是孔径的尺寸,一个大于1的奇数。比如这里是5,中值滤波器就会使用5×5的范围来计算

ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY, 11, 2)
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 11, 2)

titles = ['Original Image', 'Global Thresholding (v = 127)', 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]

for i in range(4):
    plt.subplot(2,2,i+1), plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()

在这里插入图片描述

# Otsu二值法
# 双峰图片(简单说,双峰图片是频率分布峰值有两个的图片),对于这种图片,我们近似的可以用两个峰的中间的值作为阈值,这就是Otsu二值法的做法
# 对于非双峰图片,二值法不准确

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('shaungfeng.jpg',0)

# global thresholding
ret1, th1= cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# Otsu's thresholding
ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# Otsu's thresholding after Gaussian filtering
blur = cv2.GaussianBlur(img,(5,5), 0)
ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# plot all the images and their histograms
images = [img, 0, th1, img, 0, th2, blur, 0, th3]
titles = ['Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)', 'Original Noisy Image', 'Histogram', "Otsu's Thresholding", 'Gaussian filtered Image', 'Histogram', "Otsu's Thresholding"]

for i in range(3):
    plt.subplot(3, 3, i*3 + 1), plt.imshow(images[i*3], 'gray')
    plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
    plt.subplot(3, 3, i*3+2), plt.hist(images[i*3].ravel(), 256)
    plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
    plt.subplot(3, 3, i*3+3), plt.imshow(images[i*3+2], 'gray')
    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])

plt.show()


在这里插入图片描述)

猜你喜欢

转载自blog.csdn.net/TingHW/article/details/84526671