欢迎大家学习OpenCV4.8 开发实战专栏,长期更新,不断分享源码。
专栏代码全部基于C++ 与Python双语演示。
送相关学习资料V : OpenCVXueTang_Asst
本文关键知识点:二值图像分析-轮廓发现
演示代码
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char *argv[])
{
Mat src = imread("D:/images/coins.jpg");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
// 去噪声与二值化
Mat dst, gray, binary;
GaussianBlur(src, dst, Size(3, 3), 0, 0);
cvtColor(dst, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
imshow("binary", binary);
imwrite("D:/binary.png", binary);
// 轮廓发现与绘制
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
for (size_t t = 0; t < contours.size(); t++) {
drawContours(src, contours, t, Scalar(0, 0, 255), 2, 8);
}
imshow("contours", src);
waitKey(0);
return 0;
}
python 代码演示
import cv2 as cv
import numpy as np
def threshold_demo(image):
# 去噪声+二值化
dst = cv.GaussianBlur(image,(3, 3), 0)
gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_OTSU | cv.THRESH_BINARY)
cv.imshow("binary", binary)
return binary
def canny_demo(image):
t = 100
canny_output = cv.Canny(image, t, t * 2)
cv.imshow("canny_output", canny_output)
return canny_output
src = cv.imread("D:/images/yuan_test.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
binary = threshold_demo(src)
# 轮廓发现
out, contours, hierarchy = cv.findContours(binary, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
for c in range(len(contours)):
cv.drawContours(src, contours, c, (0, 0, 255), 2, 8)
# 显示
cv.imshow("contours-demo", src)
cv.waitKey(0)
cv.destroyAllWindows()
结束语
学习贵在坚持,学习OpenCV贵在每一天的代码练习,原理跟基本的函数解释,相关知识,后续更新边学边理解,搞技术永远要坚持做长期主义者!我们一起努力!!!
送相关学习资料,V: OpenCVXueTang_Asst