opencv-041-基本阈值操作 发表于 2019-04-13 | 分类于 opencv 知识点 API 12345678910111213double cv::threshold( InputArray src, OutputArray dst, double thresh, double maxval, int type)其中type表示阈值分割的方法,支持如下五种:THRESH_BINARY = 0 二值分割THRESH_BINARY_INV = 1 反向二值分割THRESH_TRUNC = 2 截断THRESH_TOZERO = 3 取零THRESH_TOZERO_INV = 4 反向取零 代码(c++,python)1234567891011121314151617181920212223242526272829303132#include <iostream>#include <opencv2/opencv.hpp>using namespace std;using namespace cv;/* * 基本阈值操作 */int main() { Mat src = imread("../images/master.jpg"); if (src.empty()) { cout << "could not load image.." << endl; } imshow("input", src); int T = mean(src)[0]; Mat gray, binary; cvtColor(src, gray, COLOR_BGR2GRAY); for (int i = 0; i < 5; ++i) {// THRESH_BINARY = 0// THRESH_BINARY_INV = 1// THRESH_TRUNC = 2// THRESH_TOZERO = 3// THRESH_TOZERO_INV = 4 threshold(gray, binary, T, 255, i); imshow(format("binary_%d", i), binary); } waitKey(0); return 0;} 1234567891011121314151617181920212223import cv2 as cvimport numpy as np## THRESH_BINARY = 0# THRESH_BINARY_INV = 1# THRESH_TRUNC = 2# THRESH_TOZERO = 3# THRESH_TOZERO_INV = 4#src = cv.imread("D:/images/master.jpg")cv.namedWindow("input", cv.WINDOW_AUTOSIZE)cv.imshow("input", src)T = 127# 转换为灰度图像gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)for i in range(5): ret, binary = cv.threshold(gray, T, 255, i) cv.imshow("binary_" + str(i), binary)cv.waitKey(0)cv.destroyAllWindows() 结果 代码地址github