opencv-081-角点检测(Harris角点检测)

知识点

角点是一幅图像上最明显与重要的特征,对于一阶导数而言,角点在各个方向的变化是最大的,而边缘区域在只是某一方向有明显变化。

API

1
2
3
4
5
6
7
8
9
10
11
12
13
void cv::cornerHarris(
InputArray src,
OutputArray dst,
int blockSize,
int ksize,
double k,
int borderType = BORDER_DEFAULT
)
src单通道输入图像
dst是输出response
blockSize计算协方差矩阵的时候邻域像素大小
ksize表示soble算子的大小
k表示系数

代码(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
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

void process_frame(Mat &image);

RNG rng(12345);

/*
* 角点检测(Harris角点检测)
*/
int main() {
Mat src = imread("../images/box.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

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

waitKey(0);
return 0;
}

void process_frame(Mat &image) {
// detector paraments
int blockSize = 2;
int kSize = 3;
double k = 0.04;

// detecting corners
Mat gray, dst;
cvtColor(image, gray, COLOR_BGR2GRAY);
cornerHarris(gray, dst, blockSize, kSize, k);

// normalizing
Mat dst_norm = Mat::zeros(dst.size(), dst.type());
normalize(dst, dst_norm, 0, 255, NORM_MINMAX);
convertScaleAbs(dst_norm, dst_norm);

// drawing a circle around corners
for (int row = 0; row < dst_norm.rows; ++row) {
for (int col = 0; col < dst_norm.cols; ++col) {
int rsp = dst_norm.at<uchar>(row, col);
if (rsp > 150) {
int b = rng.uniform(0, 256);
int g = rng.uniform(0, 256);
int r = rng.uniform(0, 256);
circle(image, Point(row, col), 5, Scalar(b, g, r), 2);
}
}
}
}
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
import numpy as np
import cv2 as cv


def process(image, opt=1):
# Detector parameters
blockSize = 2
apertureSize = 3
k = 0.04
# Detecting corners
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
dst = cv.cornerHarris(gray, blockSize, apertureSize, k)
# Normalizing
dst_norm = np.empty(dst.shape, dtype=np.float32)
cv.normalize(dst, dst_norm, alpha=0, beta=255, norm_type=cv.NORM_MINMAX)
dst_norm_scaled = cv.convertScaleAbs(dst_norm)
# Drawing a circle around corners
for i in range(dst_norm.shape[0]):
for j in range(dst_norm.shape[1]):
if int(dst_norm[i, j]) > 80:
b = np.random.random_integers(0, 256)
g = np.random.random_integers(0, 256)
r = np.random.random_integers(0, 256)
cv.circle(image, (j, i), 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