python - 改进 Canny 边缘检测

标签 python opencv image-processing

当我在图纸上运行 cv.Canny 边缘检测器时,它会检测到数百个密集填充在阴影区域中的小边缘。我怎样才能让它停止这样做,同时仍然检测到眼睛和 Nose 等较轻的特征?我也试过模糊。

这是一个示例,与 online photo tool 相比.

Original image .
Output of online tool .
My python program

这是我的代码:

def outline(image, sigma = 5):
    image = cv.GaussianBlur(image, (11, 11), sigma)
    ratio = 2
    lower = .37 * 255
    upper = lower * ratio
    outlined = cv.Canny(image, lower, upper)

    return outlined

我该如何改进它?

最佳答案

这是在 Python/OpenCV 中执行此操作的一种方法。

形态边缘输出是蒙版和扩张蒙版之间的绝对差异

  • 阅读输入
  • 转为灰色
  • 阈值(作为掩码)
  • 扩大阈值图像
  • 计算绝对差值
  • 将其极性反转为边缘图像
  • 保存结果

  • 输入:

    enter image description here
    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread("cartoon.jpg")
    
    # convert to gray
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # threshold
    thresh = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY)[1]
    
    # morphology edgeout = dilated_mask - mask
    # morphology dilate
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    dilate = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, kernel)
    
    # get absolute difference between dilate and thresh
    diff = cv2.absdiff(dilate, thresh)
    
    # invert
    edges = 255 - diff
    
    # write result to disk
    cv2.imwrite("cartoon_thresh.jpg", thresh)
    cv2.imwrite("cartoon_dilate.jpg", dilate)
    cv2.imwrite("cartoon_diff.jpg", diff)
    cv2.imwrite("cartoon_edges.jpg", edges)
    
    # display it
    cv2.imshow("thresh", thresh)
    cv2.imshow("dilate", dilate)
    cv2.imshow("diff", diff)
    cv2.imshow("edges", edges)
    cv2.waitKey(0)
    

    阈值图像:

    enter image description here

    扩张阈值图像:

    enter image description here

    差异图像:

    enter image description here

    边缘图像:

    enter image description here

    关于python - 改进 Canny 边缘检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61643039/

    相关文章:

    image - 检测照片与渲染图像

    python - 分配列表理解、差异

    python - 需要输入: Linear Regression prediction of difficulty of routes quite bad

    python - DJango 设置中的 SECURE_PROXY_SSL_HEADER 导致 CORS 预检 301 响应状态代码(和失败)

    python - findChessboardCorners() 返回的角数组的形状

    opencv - 使用卡尔曼滤波器的 3D 对象位置预测,可变时间段

    python - 通过 Image.fromarray 将 float 图像数组转换为 PIL 中的 int

    python - Django postgresql 外键

    django - Python opencv等待相机空闲

    python - Keras:打印出预测的类标签