getTrackbarPos
此方法可以通过滑动的方式调节阈值大小
import cv2 as cv
import numpy as np
src = cv.imread("gapPic.jpg")
gray_img = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
def nothing():
pass
cv.namedWindow("bar")
cv.createTrackbar("threshold1", "bar", 0, 255, nothing)
cv.createTrackbar("threshold2", "bar", 0, 255, nothing)
dst = cv.equalizeHist(gray_img)
# 高斯滤波降噪
gaussian = cv.GaussianBlur(dst, (9, 9), 0)
cv.imshow("gaussian", gaussian)
while True:
threshold1 = cv.getTrackbarPos("threshold1", "bar")
threshold2 = cv.getTrackbarPos("threshold2", "bar")
# 边缘检测
edges = cv.Canny(gaussian, threshold1, threshold2)
cv.imshow("edges", edges)
if cv.waitKey(1) & 0xFF == 27:
break
cv.destroyAllWindows()
calcHist
获取直方图
hist = cv2.calcHist([gray_img], [0], None, [256], [0, 255])
plt.figure(figsize=(10, 5))
plt.title(title)
plt.plot(hist, color='k')
plt.show()
plt.close()
霍夫变换
用于检车图像中的直线、圆
# 直线检测
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=50, maxLineGap=5)
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(rec_img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 原理详解:https://zhuanlan.zhihu.com/p/141546789| https://zhuanlan.zhihu.com/p/450353060
模板匹配
method = 1
# img_templ = cv2.imdecode(np.fromfile(self.template_path, dtype=np.uint8), -1)
img_templ = cv2.cvtColor(img_templ, cv2.COLOR_BGR2GRAY)
img_gauss = cv2.GaussianBlur(img_copy, (9, 9), 0)
# img_med = cv2.medianBlur(img_copy, 5) # 中值滤波
result = cv2.matchTemplate(img_gauss, img_templ, method)
min_max = cv2.minMaxLoc(result) # 获取结果中最小值,最大值,并得到最大值,最小值的索引
if method == 0 or method == 1: # 根据不同的模式最佳匹配位置取值方法不同
match_loc = min_max[2]
else:
match_loc = min_max[3]
# 注意计算右下角坐标时x坐标要加模板图像shape[1]表示的宽度,y坐标加高度
right_bottom = (match_loc[0] + img_templ.shape[1], match_loc[1] + img_templ.shape[0])
# 原理详解:https://blog.csdn.net/qq_46418503/article/details/119675943