python图像二值化处理
一、图像二值化
图像二值化是指将图像上像素点的灰度值设定为0或255,即整个图像呈现明显的黑白效果的过程。
二、python图像二值化处理
1.opencv简单阈值cv2.threshold
2.opencv自适应阈值cv2.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相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python cmd中怎么运行python文件
运行Python,可在交互模式下运行,或者命令行中。命令行中运行的是Python的.py文件。cmd中执行Python程序的方法,如下打开cmdC:\Users\Administ...详情>>
2023-11-06 14:37:04
pythondict是啥意思
Python中的dict表示的字典数据类型。字典是另一种可变容器模型,且可存储任意类型对象。字典是python语言中唯一的映射类型映射类型对象里哈希值...详情>>
2023-11-06 13:56:05
python如何创建模块
Python模块(Module),是一个Python文件,以.py结尾,包含了Python对象定义和Python语句。模块让你能够有逻辑地组织你的Python代码段。把相关的...详情>>
2023-11-06 13:36:31
python解释器写代码如何换行
使用以下方法可以使Python的代码换行:用反斜杠链接多行代码,示例输出:55a=22+\33printa用小括号括起来,示例输出:55a=(22+33)printa提示:针...详情>>
2023-11-06 13:17:12热门推荐
技术干货






