怎么在python中处理图像二值化

怎么在python中处理图像二值化?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

成都创新互联是一家专业提供辽阳企业网站建设,专注与网站设计制作、成都网站建设、H5网站设计、小程序制作等业务。10年已为辽阳众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

一、图像二值化

图像二值化是指将图像上像素点的灰度值设定为0或255,即整个图像呈现明显的黑白效果的过程。

二、python图像二值化处理

1.opencv简单阈值cv2.threshold

2.opencv自适应阈值cv2.adaptiveThreshold

有两种方法可用于计算自适应阈值:mean_c和guassian_c

3.Otsu's二值化

三、示例:

import cv2
import numpy as np
from matplotlib import pyplot as plt
 
img = cv2.imread('scratch.png', 0)
# global thresholding
ret1, th2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# Otsu's thresholding
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
# Otsu's thresholding
# 阈值一定要设为 0 !
ret3, th4 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# plot all the images and their histograms
images = [img, 0, th2, img, 0, th3, img, 0, th4]
titles = [
  'Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)',
  'Original Noisy Image', 'Histogram', "Adaptive Thresholding",
  'Original Noisy Image', 'Histogram', "Otsu's Thresholding"
]
# 这里使用了 pyplot 中画直方图的方法, plt.hist, 要注意的是它的参数是一维数组
# 所以这里使用了( numpy ) ravel 方法,将多维数组转换成一维,也可以使用 flatten 方法
# ndarray.flat 1-D iterator over an array.
# ndarray.flatten 1-D array copy of the elements of an array in row-major order.
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()

看完上述内容,你们掌握怎么在python中处理图像二值化的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


网站名称:怎么在python中处理图像二值化
网站网址:http://pwwzsj.com/article/ggjgjs.html