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("./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()
C++代码:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char *argv[])
{
Mat src = imread("./test.png");
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("./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;
}
图像连通组件分析,可以得到二值图像的每个连通组件,但是我们还无法得知各个组件之间的层次关系与几何拓扑关系,如果我们需要进一步分析图像轮廓拓扑信息就可以通过OpenCV的轮廓发现API获取二值图像的轮廓拓扑信息,轮廓发现API如下:
当thickness为正数的时候表示绘制该轮廓 当thickness为-1表示填充该轮廓
OpenCV学习笔记代码,欢迎follow:
MachineLP/OpenCV-github.com