python opencv入门 图像阈值(10)
来源:互联网 发布:网络共享电脑打不开 编辑:程序博客网 时间:2024/05/29 11:20
内容来自OpenCV-Python Tutorials 自己翻译整理
目标:
学习自适应阈值控制,Otsu阈值,等等
学习函数 cv2.threshold, cv2.adaptiveThreshold等等
简单阈值:
原理很直接,如果像素值大于一个阈值,那么久将它赋值一个数,否则赋值成另外一个数。函数使用cv2.threshold
第一参数是原图像,而且这个图像应该是一个灰度图像。第二个参数用来区分像素的阈值。第三个参数是像素值大于阈值时的上限。opencv提供了不同样式的阈值并且由第四个参数决定。类型如下
cv2.THRESH_BINARY
cv2.THRESH_BINARY_INV
cv2.THRESH_TRUNC
cv2.THRESH_TOZERO
cv2.THRESH_TOZERO_INV
参数见名知意
有两个输出结果,第一个是retval,后面解释。第二个数阈值处理后的图片。
import cv2import numpy as npfrom matplotlib import pyplot as pltimg = cv2.imread('4.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()
自适应阈值
前面部分使用了全局值作为阈值。在图片光照条件不同的情况下可能效果不好。现在选用自适应阈值,该算法计算图片一小部分区域的阈值。所以可以获得相同图片不同区域的阈值,并且能提供给用户在变化光照情况系下更好的结果。
有三个特别的输入参数,只有一个输出。
第一个参数:自适应方法 决定阈值如何被计算。
- cv2.ADAPTIVE_THRESH_MEAN_C 阈值取邻近区域的平均值
- cv2.ADAPTIVE_THRESH_GAUSSIAN_C 阈值取带权邻近区域值的和,并且权值是高斯窗口
第二个参数:区域大小
邻近区域的大小
第三个参数:在计算均值和带权均值时减去的常量。
下面例子是对比全局阈值和自适应阈值在不同光照情况的效果
import cv2import numpy as npfrom matplotlib import pyplot as pltimg = cv2.imread('6.jpg',0)img = cv2.medianBlur(img,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二值化
上面说的retval参数可以在Otsu时用到
在全局变量的阈值当中,使用一个比较模糊的值,那么怎么才能知道选择的值是好是坏?答案是实验和尝试法。考虑一个双峰的图像(就是图像的直方图有两个峰值)。对于图像,我们可以大约的取到一个在两个峰值之间的值作为阈值。这就是Otsu二值化的方法。所以,这种方法自动的在双峰图像的图像直方图中计算一个阈值。(如果不是双峰图像,二值化效果不准(废话~))
在cv2.threshold()函数当中传入cv2.THRESH_OTSU即可。对于阈值参数,传入0即可。算法会自动寻找最优的阈值并且返回值是retVal。如果Otsu的阈值方法没有使用,retVal和普通的阈值一样。
下面的是一个有噪声的图片,首先使用全局阈值127,在第二个例子当中是用Otsu阈值,在第三个例子当中,使用5*5的高斯滤波去除噪声,然后再用Otsu
(原代码是python2 我的编译环境是python3)
import cv2import numpy as npfrom matplotlib import pyplot as pltimg = cv2.imread('6.jpg',0)# global thresholdingret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)# Otsu's thresholdingret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)# Otsu's thresholding after Gaussian filteringblur = 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 histogramsimages = [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()
Otsu二值化是如何工作的?
Otsu算法找一个阈值,这个阈值使加权内方差最小
(公式没解释,没看懂-_-)
公式实现
import cv2import numpy as npimg = cv2.imread('6.jpg',0)blur = cv2.GaussianBlur(img,(5,5),0)# find normalized_histogram, and its cumulative distribution functionhist = cv2.calcHist([blur],[0],None,[256],[0,256])hist_norm = hist.ravel()/hist.max()Q = hist_norm.cumsum()bins = np.arange(256)fn_min = np.infthresh = -1for i in range(1,256): p1,p2 = np.hsplit(hist_norm,[i]) # probabilities q1,q2 = Q[i],Q[255]-Q[i] # cum sum of classes b1,b2 = np.hsplit(bins,[i]) # weights # finding means and variances m1,m2 = np.sum(p1*b1)/q1, np.sum(p2*b2)/q2 v1,v2 = np.sum(((b1-m1)**2)*p1)/q1,np.sum(((b2-m2)**2)*p2)/q2 # calculates the minimization function fn = v1*q1 + v2*q2 if fn < fn_min: fn_min = fn thresh = i# find otsu's threshold value with OpenCV functionret, otsu = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)print(thresh)print(ret)
- python opencv入门 图像阈值(10)
- Python-OpenCV图像阈值
- 图像阈值化(Python+opencv)
- openCV—Python(10)——图像阈值化处理
- openCV—Python(10)——图像阈值化处理
- OpenCV-Python——图像阈值
- opencv图像阈值设置
- opencv-----图像阈值化
- opencv 图像阈值分割图像
- Python下opencv使用笔记(四)(图像的阈值处理)
- Opencv3.0-python的那些事儿:(四)、Opencv的图像阈值处理
- python opencv入门 图像平滑(12)
- python opencv入门 图像梯度(14)
- python opencv入门 图像金字塔(16)
- OpenCV入门(十二)-- 阈值化
- opencv阈值法分割图像
- OpenCV图像的阈值化
- OpenCV实现图像阈值化
- 【Java笔记】单例模式设计模式
- [LeetCode] 3Sum 三数之和 Python
- LBP特征识别
- Acdreamer博客数论学习(1)
- 位运算常见面试题
- python opencv入门 图像阈值(10)
- 'JSON字符串' 标准形式及解析方式
- ZOJ
- POJ
- Java导入csv文件以及解决中文乱码
- Java中静态代码块、非静态代码块、构造方法三者的执行顺序
- js基础知识
- BootStrap 时间控件 bootstrap-datetimepicker 火狐浏览器报错m is undefined
- 多文件编辑