python图像二值化处理
发布时间:2025-11-10 16:42:56

一、图像二值化
图像二值化是指将图像上像素点的灰度值设置为0或255,即整个图像呈现明显的黑白效果的过程。
二、python图像二值化处理
1.cv2opencv简单阈值.threshold
2.cv2opencv自适应阈值.adaptiveThreshold
计算自适应阈值有两种方法:mean_c和guassian_c
3.Otsu's二值化
三、示例:
importcv2
importnumpyasnp
frommatplotlibimportpyplotasplt
img=cv2.imread('scratch.png',0)
#globalthresholding
ret1,th1=cv2.threshold(img,127,255,cv2.THRESH_BINARY)
#Otsu'sthresholding
th2=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
#Otsu'sthresholding
#阈值必须设为0!
ret3,th3=cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
#plotalltheimagesandtheirhistograms
images=[img,0,th1,img,0,th2,img,0,th3]
titles=[
'OriginalNoisyImage','Histogram','GlobalThresholding(v=127)',
'OriginalNoisyImage','Histogram',"AdaptiveThresholding",
'OriginalNoisyImage','Histogram',"Otsu'sThresholding"
]
#采用pyplot中画直方图的方法,plt.hist,需要注意的是,它的参数是一维数组
#所以在这里使用(numpy)将多维数组转换为一维的ravel方法,也可以使用flatten方法
#ndarray.flat1-Diteratoroveranarray.
#ndarray.flatten1-Darraycopyoftheelementsofanarrayinrow-majororder.
foriinrange(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()建议查看图像二值化相关知识点:
python全局图像二值化
如何二值化图像?
更多python学习欢迎来到python学习网,免费分享python学习教程和视频!
下一篇 python图像处理是啥
