opencv python

python中怎么使用opencv实现阈值分割

小亿
97
2023-08-14 21:06:50
栏目: 编程语言

在Python中使用OpenCV实现阈值分割可以按照以下步骤进行:

  1. 导入OpenCV库:
import cv2
  1. 读取图像:
img = cv2.imread('image.jpg', 0) # 读取灰度图像
  1. 对图像进行阈值分割:
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

这里的127是阈值,255是最大像素值,cv2.THRESH_BINARY是阈值分割类型,表示将大于阈值的像素设置为最大像素值,小于阈值的像素设置为0。

  1. 显示分割结果:
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.imshow()用于显示图像窗口,cv2.waitKey(0)用于等待键盘输入,cv2.destroyAllWindows()用于关闭所有图像窗口。

完整的代码示例:

import cv2
# 读取图像
img = cv2.imread('image.jpg', 0)
# 阈值分割
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 显示分割结果
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

注意:在上述代码中,image.jpg是待分割的图像文件名,需要根据实际情况进行替换。

0
看了该问题的人还看了