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

手机站
千锋教育

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

千锋教育

扫一扫进入千锋手机站

领取全套视频
千锋教育

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

当前位置:首页  >  技术干货  > python图像二值化处理

python图像二值化处理

来源:千锋教育
发布人:qyf
时间: 2022-08-17 17:38:00 1660729080

python图像二值化处理

  一、图像二值化

  图像二值化是指将图像上像素点的灰度值设定为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, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

  # Otsu's thresholding

  th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)

  # Otsu's thresholding

  # 阈值一定要设为 0 !

  ret3, th3 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

  # plot all the images and their histograms

  images = [img, 0, th1, img, 0, th2, img, 0, th3]

  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培训”的问题,欢迎咨询千锋教育在线名师。千锋教育多年办学,课程大纲紧跟企业需求,更科学更严谨,每年培养泛IT人才近2万人。不论你是零基础还是想提升,都可以找到适合的班型,千锋教育随时欢迎你来试听。

tags:
声明:本站稿件版权均属千锋教育所有,未经许可不得擅自转载。
10年以上业内强师集结,手把手带你蜕变精英
请您保持通讯畅通,专属学习老师24小时内将与您1V1沟通
免费领取
今日已有369人领取成功
刘同学 138****2860 刚刚成功领取
王同学 131****2015 刚刚成功领取
张同学 133****4652 刚刚成功领取
李同学 135****8607 刚刚成功领取
杨同学 132****5667 刚刚成功领取
岳同学 134****6652 刚刚成功领取
梁同学 157****2950 刚刚成功领取
刘同学 189****1015 刚刚成功领取
张同学 155****4678 刚刚成功领取
邹同学 139****2907 刚刚成功领取
董同学 138****2867 刚刚成功领取
周同学 136****3602 刚刚成功领取
相关推荐HOT