千锋教育-做有情怀、有良心、有品质的职业教育机构

400-811-9990
手机站
千锋教育

千锋学习站 | 随时随地免费学

千锋教育

扫一扫进入千锋手机站

领取全套视频
千锋教育

关注千锋学习站小程序
随时随地免费学习课程

上海
  • 北京
  • 郑州
  • 武汉
  • 成都
  • 西安
  • 沈阳
  • 广州
  • 南京
  • 深圳
  • 大连
  • 青岛
  • 杭州
  • 重庆
当前位置:武汉千锋IT培训  >  技术干货  >  python图像二值化处理

python图像二值化处理

来源:千锋教育
发布人:xqq
时间: 2023-11-11 23:31:37

一、图像二值化

图像二值化是指将图像上像素点的灰度值设定为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培训机构:千锋教育。

声明:本站稿件版权均属千锋教育所有,未经许可不得擅自转载。

猜你喜欢LIKE

在python中如何打乱数据?

2023-11-11

python架构是什么?

2023-11-11

python 列表排序

2023-11-11

最新文章NEW

python 抽象类和接口类

2023-11-11

python 的 Keras函数式模型

2023-11-11

Python生成表达式和列表解析

2023-11-11

相关推荐HOT

更多>>

快速通道 更多>>

最新开班信息 更多>>

网友热搜 更多>>