opencv(三 阈值调节、直方图、霍夫变换、模板匹配)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值