#!--*-- coding=utf-8 --*--
import cv2
import os
import argparse

'''
基于OpenCV Canny 算子的提取图像边缘
'''

#
def edge_extract(in_file, out_file, lowThreshold=10, Gaussianblur_size=19):
    '''
    :param in_file:
    :param out_file:
    :param lowThreshold: 阈值, 如:low - 10; medium - 23; high - 60
    '''

    img = cv2.imread(in_file)
    if img is None:
        return 'Please check input image.'

    # 对BGR三个通道分别检测边缘
    grayB = img[:, :, 0]
    grayG = img[:, :, 1]
    grayR = img[:, :, 2]
    # 高斯模糊过滤掉部分细节
    blurB = cv2.GaussianBlur(grayB, (Gaussianblur_size, Gaussianblur_size), 0)
    blurG = cv2.GaussianBlur(grayG, (Gaussianblur_size, Gaussianblur_size), 0)
    blurR = cv2.GaussianBlur(grayR, (Gaussianblur_size, Gaussianblur_size), 0)
    # opencv Canny算法
    highThreshold = lowThreshold * 2  # Canny算子的阈值上限
    edges_B = cv2.Canny(blurB, lowThreshold, highThreshold, apertureSize=3)
    edges_G = cv2.Canny(blurG, lowThreshold, highThreshold, apertureSize=3)
    edges_R = cv2.Canny(blurR, lowThreshold, highThreshold, apertureSize=3)
    # 3个通道分别提取的边缘融合到一块
    edge = cv2.bitwise_or(edges_B, edges_G)
    edge = cv2.bitwise_or(edge, edges_R)
    # 默认生成的是黑底白边缘线, 故黑白反转,使背景为白色,边缘线为黑色
    edge = 255 - edge
    cv2.imwrite(out_file, edge)


def parse_args():
    """Parse input arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', dest='input')
    parser.add_argument('-o', dest='output')
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = parse_args()
    edge_extract(args.input, args.output)

    print('[INFO]Done.')

Last modification:November 30th, 2019 at 10:34 am