python openCV学习——常用算法


原图
在这里插入图片描述
下面的 show_img方法是封装了 cv2.imshow()cv2.waitKey(),方便我自己使用,不用每次输入窗口名称,不用每次都waitKey。

形态学操作

腐蚀,膨胀,开,闭,就不掩饰了。
源码

def main():
    """
    测试形态学操作
    :return:
    """
    img_path = "./pictures/icons/screenshot.jpg"
    img = cv2.imread(img_path)

    show_img(img)

    # 进行形态学梯度运算
    k = np.ones((2,2), np.int) # 核
    r = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, k) # 形态学梯度运算
    show_img(r)

    # 礼帽运算
    k = np.ones((2, 2), np.int)  # 核
    r = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, k)  # 礼帽运算
    show_img(r)

    # 黑帽运算
    k = np.ones((2, 2), np.int)  # 核
    r = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, k)  # 黑帽运算
    show_img(r)

形态学梯度运算结果
在这里插入图片描述
礼帽运算结果
在这里插入图片描述
黑帽运算结果

在这里插入图片描述

Sobel算子,Scharr算子和Laplacian算子

源码

def main():
    """
    测试图像梯度
    :return:
    """
    img_path = "./pictures/icons/screenshot.jpg"
    img = cv2.imread(img_path)

    show_img(img)

    sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0)
    sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1)
    sobel_x = cv2.convertScaleAbs(sobel_x)
    sobel_y = cv2.convertScaleAbs(sobel_y)
    sobel_xy = cv2.addWeighted(sobel_x, 0.5, sobel_y, 0.5, 0)

    show_img(sobel_xy)

    scharr_x = cv2.Scharr(img, cv2.CV_64F, 1, 0)
    scharr_y = cv2.Scharr(img, cv2.CV_64F, 0, 1)
    scharr_x = cv2.convertScaleAbs(scharr_x)
    scharr_y = cv2.convertScaleAbs(scharr_y)
    scharr_xy = cv2.addWeighted(scharr_x, 0.5, scharr_y, 0.5, 0)

    show_img(scharr_xy)

    laplacian = cv2.Laplacian(img, cv2.CV_64F)
    laplacian = cv2.convertScaleAbs(laplacian)

    show_img(laplacian)

Sobel算子
在这里插入图片描述
Scharr算子
在这里插入图片描述
Laplacian算子
在这里插入图片描述

Canny 边缘检测

源码

def main():
    """
    Canny 边缘检测
    :return:
    """
    img_path = "./pictures/icons/screenshot.jpg"
    img = cv2.imread(img_path)

    r1 = cv2.Canny(img, 128, 200)
    r2 = cv2.Canny(img, 32, 128)

    show_img(r1)
    show_img(r2)

两种不同的核的结果
在这里插入图片描述
在这里插入图片描述

findContours图像轮廓

源码

def main5():
    """
    查找图像轮廓
    :return:
    """
    img_path = "./pictures/icons/screenshot.jpg"
    img = cv2.imread(img_path)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    o = cv2.drawContours(img, contours, -1, (0,255,255), 1)
    show_img(o)

结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值