我使用的是最基础,精确度最低的方法,我可这真是太菜了
代码很简单,那些函数百度一下就可以搜到了,我就不详细讲了。写这篇文章的目的是,我之前做过很多程序中其实都用过这些函数,但是哪些程序在我改了一边又一边之后有的函数就没用,现在我要再用就要重新搜这些函数怎么用的,所以我决定写一个程序就发一个,方便我找。唉,我真菜(嚎啕大哭)
import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('demo/1.jpg')
target = cv2.imread('demo/11.jpg')
th, tw = target.shape[:2]
# 进行模板匹配
result = cv2.matchTemplate(target, img1, cv2.TM_SQDIFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
tl = min_loc
br = (tl[0] + tw, tl[1] + th)
# 绘制矩形
cv2.rectangle(img1, tl, br, (0, 0, 255), 2)
l_img = img1[tl[1] + 2:tl[1] + th-2, tl[0]+2:tl[0] + tw-2]
grey = cv2.cvtColor(l_img, cv2.COLOR_BGR2GRAY)
gaussian = cv2.GaussianBlur(grey, (3, 3), 0)
# HoughCircles方法检测图中的圆形
circles1 = cv2.HoughCircles(gaussian, cv2.HOUGH_GRADIENT, 1, 100, param1=100, param2=30, minRadius=15, maxRadius=80)
circles = circles1[0, :, :]
circles = np.uint16(np.around(circles))
for i in circles[:]:
cv2.circle(grey, (i[0], i[1]), i[2], (0, 255, 0), 3) # 画圆
edges = cv2.Canny(grey, 50, 120)
minLineLength = 100
maxLineGap = 40
# HoughLinesP检测图中的直线
lines = cv2.HoughLinesP(edges, 1.0, np.pi / 180, 20, minLineLength, maxLineGap)
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(l_img, (x1, y1), (x2, y2), (0, 255, 0), 1)
x1 = float(x1)
x2 = float(x2)
y1 = float(y1)
y2 = float(y2)
# 计算斜率
if x2 - x1 == 0:
print("直线是竖直的")
result = 90
elif y2 - y1 == 0:
print("直线是水平的")
result = 0
else:
k = -(y2 - y1) / (x2 - x1)
# 求反正切,再将得到的弧度转换为度
result = np.arctan(k) * 57.29577
print("直线倾斜角度为:" + str(result) + "度")
cv2.namedWindow("img", 0)
cv2.namedWindow("img_3", 0)
cv2.imshow("img", img1)
cv2.imshow("img_3", l_img)
cv2.waitKey(0)
cv2.destroyAllWindows()