python-opencv-cv2.threshold()二值化函数详解
opencv
OpenCV: 开源计算机视觉库
项目地址:https://gitcode.com/gh_mirrors/opencv31/opencv
·
1.cv2.threshold()参数说明
cv2.threshold(src, thresh, maxval, type[, dst]) → retval, dst
| 参数 | 描述 |
|---|---|
| src | 表示的是图片源 |
| thresh | 表示的是阈值(起始值) |
| maxval | 表示的是最大值 |
| type | 表示的是这里划分的时候使用的是方法选择参数 |
常用值为0(cv2.THRESH_BINARY)
第四个是一个方法选择参数,常用的有:
• cv2.THRESH_BINARY(黑白二值)
• cv2.THRESH_BINARY_INV(黑白二值反转)
• cv2.THRESH_TRUNC (得到的图像为多像素值)
• cv2.THRESH_TOZERO
• cv2.THRESH_TOZERO_INV
该函数有两个返回值,retVal:得到的阈值,dst:阈值化后的图像
公式中0代表黑,设置最大阈值maxval为255(白)就可以进行二值化处理
2.代码示例
import cv2
import numpy as np
# 读取照片
img=cv2.imread('D:\\Patrick_Star.jpg')
# 图像缩放
img = cv2.resize(img,None,fx=0.1,fy=0.1)
cv2.imshow('img',img))
# 灰度处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray',gray)
# cv2.threshold()二值化
_,thres = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('thres',thres)
# 展示图片
cv2.waitKey(0)
cv2.destroyAllWindows()

OpenCV: 开源计算机视觉库
最近提交(Master分支:4 个月前 )
1f47f5ba
imgproc: replace assertion in cornerSubPix with descriptive error #28404
Replace CV_Assert with explicit bounds check for initial corners in cornerSubPix.
This provides a descriptive runtime error instead of abrupt termination,
improving error handling for Python and C++ users.
No algorithmic or behavioral change for valid inputs.
Fixes #25139 (Related to #7276).
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
11 小时前
fba658b9
Improve precision of RotatedRect::points 1 天前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)