opencv-082-角点检测(shi-tomas角点检测)

知识点

Harris角点检测是一种计算速度很慢的角点检测算法,很难实时计算,所有最常用的是shi-tomas角点检测算法,它的运行速度很快。

API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void cv::goodFeaturesToTrack(
InputArray image,
OutputArray corners,
int maxCorners,
double qualityLevel,
double minDistance,
InputArray mask = noArray(),
int blockSize = 3,
bool useHarrisDetector = false,
double k = 0.04
)
src单通道输入图像,八位或者浮点数
corners是输出的关键点坐标集合
maxCorners表示最大返回关键点数目
qualityLevel表示拒绝的关键点 R < qualityLevel × max response将会被直接丢弃
minDistance 表示两个关键点之间的最短距离
mask 表示mask区域,如果有表明只对mask区域做计算
blockSize 计算梯度与微分的窗口区域
useHarrisDetector 表示是否使用harris角点检测,默认是false 为shi-tomas
k = 0.04默认值,当useHarrisDetector为ture时候起作用

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

void process_frame(Mat &image);

RNG rng(12345);

/*
* 角点检测(shi-tomas角点检测)
*/
int main() {
VideoCapture capture("../images/color_object.mp4");
if (!capture.isOpened()) {
cout << "could not open video..." << endl;
return -1;
}

Mat frame;
while (true) {
bool ret = capture.read(frame);
imshow("input", frame);
if (!ret) break;

process_frame(frame);
imshow("result", frame);

char c = waitKey(5);
if (c == 27) {
break;
}
}

waitKey(0);
return 0;
}

void process_frame(Mat &image) {
// Detector parameters
int maxCorners = 100;
double quality_level = 0.01;
double minDistance = 0.04;

// detecting corners
Mat gray, dst;
cvtColor(image, gray, COLOR_BGR2GRAY);
vector<Point2f> corners;
goodFeaturesToTrack(gray, corners, maxCorners, quality_level,
minDistance, Mat(), 3, false);

// drawing corner
for (int i = 0; i < corners.size(); ++i) {
int b = rng.uniform(0, 255);
int g = rng.uniform(0, 255);
int r = rng.uniform(0, 255);
circle(image, corners[i], 5, Scalar(b, g, r), 3);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import numpy as np
import cv2 as cv


def process(image, opt=1):
# Detecting corners
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
corners = cv.goodFeaturesToTrack(gray, 100, 0.05, 10)
print(len(corners))
for pt in corners:
print(pt)
b = np.random.random_integers(0, 256)
g = np.random.random_integers(0, 256)
r = np.random.random_integers(0, 256)
x = np.int32(pt[0][0])
y = np.int32(pt[0][1])
cv.circle(image, (x, y), 5, (int(b), int(g), int(r)), 2)
# output
return image


src = cv.imread("D:/images/ele_panel.png")
cv.imshow("input", src)
result = process(src)
cv.imshow('result', result)
cv.waitKey(0)
cv.destroyAllWindows()
"""
cap = cv.VideoCapture(0)
while True:
ret, frame = cap.read()
cv.imwrite("D:/input.png", frame)
cv.imshow('input', frame)
result = process(frame)
cv.imshow('result', result)
k = cv.waitKey(5)&0xff
if k == 27:
break
cap.release()
cv.destroyAllWindows()
"""

结果

代码地址

github