当前位置: 首页>>代码示例>>Python>>正文


Python cv2.Canny方法代码示例

本文整理汇总了Python中cv2.Canny方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.Canny方法的具体用法?Python cv2.Canny怎么用?Python cv2.Canny使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cv2的用法示例。


在下文中一共展示了cv2.Canny方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: canny

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def canny(filepathname, left=70, right=140):
    v = cv2.imread(filepathname)
    s = cv2.cvtColor(v, cv2.COLOR_BGR2GRAY)
    s = cv2.Canny(s, left, right)
    cv2.imshow('nier',s)
    return s

    # 圈出最小方矩形框,这里Canny算法后都是白色线条,所以取色范围 127-255 即可。
    # ret, binary = cv2.threshold(s,127,255,cv2.THRESH_BINARY) 
    # contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    # for c in contours:
    #     x,y,w,h = cv2.boundingRect(c)
    #     if w>5 and h>10: # 有约束的画框
    #         cv2.rectangle(v,(x,y),(x+w,y+h),(155,155,0),1)
    # # cv2.drawContours(s,contours,-1,(0,0,255),3) # 画所有框
    # cv2.imshow('nier2',v)

    # cv2.waitKey()
    # cv2.destroyAllWindows() 
开发者ID:cilame,项目名称:vrequest,代码行数:21,代码来源:pycv2.py

示例2: find_squares

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:22,代码来源:squares.py

示例3: detect_lines

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def detect_lines(self, canny_low_thresh, canny_high_thresh, canny_kernel_size,
                     hough_rho_res, hough_theta_res, hough_votes_thresh,
                     gray_conversion=cv2.COLOR_BGR2GRAY):
        """
        Detect lines in input image using hough transform.
        Return detected lines as list with tuples:
        (rho, theta, normalized theta with 0 <= theta_norm < np.pi, DIRECTION_VERTICAL or DIRECTION_HORIZONTAL)
        """
        
        self.gray_img = cv2.cvtColor(self.input_img, gray_conversion)
        self.edges = cv2.Canny(self.gray_img, canny_low_thresh, canny_high_thresh, apertureSize=canny_kernel_size)
        
        # detect lines with hough transform
        lines = cv2.HoughLines(self.edges, hough_rho_res, hough_theta_res, hough_votes_thresh)
        if lines is None:
            lines = []
        
        self.lines_hough = self._generate_hough_lines(lines)
        
        return self.lines_hough 
开发者ID:WZBSocialScienceCenter,项目名称:pdftabextract,代码行数:22,代码来源:imgproc.py

示例4: make_edge_smooth

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def make_edge_smooth(dataset_name, img_size) :
    check_folder('./dataset/{}/{}'.format(dataset_name, 'trainB_smooth'))

    file_list = glob('./dataset/{}/{}/*.*'.format(dataset_name, 'trainB'))
    save_dir = './dataset/{}/trainB_smooth'.format(dataset_name)

    kernel_size = 5
    kernel = np.ones((kernel_size, kernel_size), np.uint8)
    gauss = cv2.getGaussianKernel(kernel_size, 0)
    gauss = gauss * gauss.transpose(1, 0)

    for f in tqdm(file_list) :
        file_name = os.path.basename(f)

        bgr_img = cv2.imread(f)
        gray_img = cv2.imread(f, 0)

        bgr_img = cv2.resize(bgr_img, (img_size, img_size))
        pad_img = np.pad(bgr_img, ((2, 2), (2, 2), (0, 0)), mode='reflect')
        gray_img = cv2.resize(gray_img, (img_size, img_size))

        edges = cv2.Canny(gray_img, 100, 200)
        dilation = cv2.dilate(edges, kernel)

        gauss_img = np.copy(bgr_img)
        idx = np.where(dilation != 0)
        for i in range(np.sum(dilation != 0)):
            gauss_img[idx[0][i], idx[1][i], 0] = np.sum(
                np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 0], gauss))
            gauss_img[idx[0][i], idx[1][i], 1] = np.sum(
                np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 1], gauss))
            gauss_img[idx[0][i], idx[1][i], 2] = np.sum(
                np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 2], gauss))

        cv2.imwrite(os.path.join(save_dir, file_name), gauss_img) 
开发者ID:taki0112,项目名称:CartoonGAN-Tensorflow,代码行数:37,代码来源:edge_smooth.py

示例5: sharpen_frame

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def sharpen_frame(old: np.ndarray) -> np.ndarray:
    """
    refine the edges of an image

    - https://answers.opencv.org/question/121205/how-to-refine-the-edges-of-an-image/
    - https://stackoverflow.com/questions/4993082/how-to-sharpen-an-image-in-opencv

    :param old:
    :return:
    """

    # TODO these args are locked and can not be changed
    blur = turn_blur(old)
    smooth = cv2.addWeighted(blur, 1.5, old, -0.5, 0)
    canny = cv2.Canny(smooth, 50, 150)
    return canny 
开发者ID:williamfzc,项目名称:stagesepx,代码行数:18,代码来源:toolbox.py

示例6: __apply_canny

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def __apply_canny(self, src, ksize=7, sigma=1.2, low_th=10, high_th=70):
        """Apply canny edge detection.

        Args:
            src (int): Input image BGR.
                       numpy.ndarray, (720, 1280, 3), 0~255

        Returns:
            dst (int): Output image.
                       numpy.ndarray, (720, 1280), 0~1

        """
        gray = cv2.cvtColor(src, cv2.COLOR_RGB2GRAY)
        blur_gray = cv2.GaussianBlur(gray,(ksize, ksize), sigma)
        dst = cv2.Canny(blur_gray, low_th, high_th) // 255

        return dst 
开发者ID:YanbaruRobotics,项目名称:PythonPilot,代码行数:19,代码来源:rule_based.py

示例7: _create_derivative

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def _create_derivative(cls, filepath):
        img = cv2.imread(filepath,0)
        edges = cv2.Canny(img, 175, 320, apertureSize=3)
        # Create gradient map using Sobel
        sobelx64f = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=-1)
        sobely64f = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=-1)

        theta = np.arctan2(sobely64f, sobelx64f)
        if diagnostics:
            cv2.imwrite('edges.jpg',edges)
            cv2.imwrite('sobelx64f.jpg', np.absolute(sobelx64f))
            cv2.imwrite('sobely64f.jpg', np.absolute(sobely64f))
            # amplify theta for visual inspection
            theta_visible = (theta + np.pi)*255/(2*np.pi)
            cv2.imwrite('theta.jpg', theta_visible)
        return (edges, sobelx64f, sobely64f, theta) 
开发者ID:mypetyak,项目名称:StrokeWidthTransform,代码行数:18,代码来源:swt.py

示例8: __init__

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def __init__(self, imgfile):
        """
        Create a new image processing object for <imgfile>.
        """
        if not imgfile:
            raise ValueError("parameter 'imgfile' must be a non-empty, non-None string")
        
        self.imgfile = imgfile
        self.input_img = None
        self.img_w = None
        self.img_h = None
                
        self.gray_img = None  # grayscale version of the input image
        self.edges = None     # edges detected by Canny algorithm
        
        self.lines_hough = []   # contains tuples (rho, theta, theta_norm, DIRECTION_HORIZONTAL or DIRECTION_VERTICAL)
        
        self._load_imgfile() 
开发者ID:WZBSocialScienceCenter,项目名称:pdftabextract,代码行数:20,代码来源:imgproc.py

示例9: test___init___single_value_hysteresis

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def test___init___single_value_hysteresis(self):
        aug = iaa.Canny(
            alpha=0.2,
            hysteresis_thresholds=[0, 1, 2],
            sobel_kernel_size=[3, 5],
            colorizer=iaa.RandomColorsBinaryImageColorizer(
                color_true=10, color_false=20)
        )
        assert is_parameter_instance(aug.alpha, iap.Deterministic)
        assert is_parameter_instance(aug.hysteresis_thresholds, iap.Choice)
        assert is_parameter_instance(aug.sobel_kernel_size, iap.Choice)
        assert isinstance(aug.colorizer, iaa.RandomColorsBinaryImageColorizer)
        assert np.isclose(aug.alpha.value, 0.2)
        assert aug.hysteresis_thresholds.a == [0, 1, 2]
        assert is_parameter_instance(aug.sobel_kernel_size, iap.Choice)
        assert aug.sobel_kernel_size.a == [3, 5]
        assert is_parameter_instance(aug.colorizer.color_true,
                                     iap.Deterministic)
        assert is_parameter_instance(aug.colorizer.color_false,
                                     iap.Deterministic)
        assert aug.colorizer.color_true.value == 10
        assert aug.colorizer.color_false.value == 20 
开发者ID:aleju,项目名称:imgaug,代码行数:24,代码来源:test_edges.py

示例10: test_get_parameters

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def test_get_parameters(self):
        alpha = iap.Deterministic(0.2)
        hysteresis_thresholds = iap.Deterministic(10)
        sobel_kernel_size = iap.Deterministic(3)
        colorizer = iaa.RandomColorsBinaryImageColorizer(
            color_true=10, color_false=20)
        aug = iaa.Canny(
            alpha=alpha,
            hysteresis_thresholds=hysteresis_thresholds,
            sobel_kernel_size=sobel_kernel_size,
            colorizer=colorizer
        )
        params = aug.get_parameters()
        assert params[0] is aug.alpha
        assert params[1] is aug.hysteresis_thresholds
        assert params[2] is aug.sobel_kernel_size
        assert params[3] is colorizer 
开发者ID:aleju,项目名称:imgaug,代码行数:19,代码来源:test_edges.py

示例11: test___str___tuple_as_hysteresis

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def test___str___tuple_as_hysteresis(self):
        alpha = iap.Deterministic(0.2)
        hysteresis_thresholds = (
            iap.Deterministic(10),
            iap.Deterministic(11)
        )
        sobel_kernel_size = iap.Deterministic(3)
        colorizer = iaa.RandomColorsBinaryImageColorizer(
            color_true=10, color_false=20)
        aug = iaa.Canny(
            alpha=alpha,
            hysteresis_thresholds=hysteresis_thresholds,
            sobel_kernel_size=sobel_kernel_size,
            colorizer=colorizer
        )
        observed = aug.__str__()
        expected = ("Canny(alpha=%s, hysteresis_thresholds=(%s, %s), "
                    "sobel_kernel_size=%s, colorizer=%s, name=UnnamedCanny, "
                    "deterministic=False)") % (
                        str(aug.alpha),
                        str(aug.hysteresis_thresholds[0]),
                        str(aug.hysteresis_thresholds[1]),
                        str(aug.sobel_kernel_size),
                        colorizer)
        assert observed == expected 
开发者ID:aleju,项目名称:imgaug,代码行数:27,代码来源:test_edges.py

示例12: edges

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def edges(mask):
  '''
    Get edges with canny detector
  '''
  # blur
  mask = cv2.GaussianBlur(mask, (5, 5), 0)

  edges = cv2.Canny(mask, 100, 200)

  # stretch
  edges = contrast_stretch(edges)

  # cast
  edges = np.uint8(edges)

  return edges 
开发者ID:PRBonn,项目名称:bonnet,代码行数:18,代码来源:plant_features.py

示例13: threshold

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def threshold(self):
        src = self.cv_read_img(self.src_file)
        if src is None:
            return

        gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)

        # 这个函数的第一个参数就是原图像,原图像应该是灰度图。
        # 第二个参数就是用来对像素值进行分类的阈值。
        # 第三个参数就是当像素值高于(有时是小于)阈值时应该被赋予的新的像素值
        # 第四个参数来决定阈值方法,见threshold_simple()
        # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
        ret, dst = cv.threshold(gray, 127, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
        self.decode_and_show_dst(dst)

    # Canny边缘检测 
开发者ID:itisyang,项目名称:ImageMiniLab,代码行数:18,代码来源:ImageMiniLab.py

示例14: canny_edge

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def canny_edge(self):
        src = self.cv_read_img(self.src_file)
        if src is None:
            return

        blurred = cv.GaussianBlur(src, (3, 3), 0)
        gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)

        grad_x = cv.Sobel(gray, cv.CV_16SC1, 1, 0)
        grad_y = cv.Sobel(gray, cv.CV_16SC1, 0, 1)

        dst = cv.Canny(grad_x, grad_y, 30, 150)
        # dst = cv.Canny(gray, 50, 150)
        self.decode_and_show_dst(dst)

    # 直线检测 
开发者ID:itisyang,项目名称:ImageMiniLab,代码行数:18,代码来源:ImageMiniLab.py

示例15: hough_line

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import Canny [as 别名]
def hough_line(self):
        src = self.cv_read_img(self.src_file)
        if src is None:
            return

        gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
        edges = cv.Canny(gray, 50, 150, apertureSize=3)
        lines = cv.HoughLines(edges, 1, np.pi/180, 200)

        for line in lines:
            rho, theta = line[0]
            a = np.cos(theta)
            b = np.sin(theta)
            x0 = a * rho
            y0 = b * rho
            x1 = int(x0+1000*(-b))
            y1 = int(y0+1000*(a))
            x2 = int(x0-1000*(-b))
            y2 = int(y0-1000*(a))
            cv.line(src, (x1, y1), (x2, y2), (0, 0, 255), 2)

        self.decode_and_show_dst(src)


    # 圆检测 
开发者ID:itisyang,项目名称:ImageMiniLab,代码行数:27,代码来源:ImageMiniLab.py


注:本文中的cv2.Canny方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。