Opencv随笔(6)--------边缘检测(API,源码实现)

1.API实现

#!/usr/bin/python
# coding:utf-8 
# 19-4-24 上午9:22
# @File    : border.py
import cv2
import os
path = os.path.join(os.getcwd(),"pic/2.jpg")
img = cv2.imread(path, 1)
shape= img.shape
#1.ctgray 2.边缘检查函数canny
src = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgs = cv2.GaussianBlur(src,(3,3), 0)
dst = cv2.Canny(imgs, 80, 80)#第二个第三个参数是门阀值
    # 低于阈值1的像素点会被认为不是边缘;
    # 高于阈值2的像素点会被认为是边缘;
    # 在阈值1和阈值2之间的像素点,若与第2步得到的边缘像素点相邻,则被认为是边缘,否则被认为不是边缘。
# cv2.Canny()

cv2.imshow("dst", dst)
cv2.waitKey()

2.opencv 源码实现

关于L2gradient参数(第四个参数):

  • 如果为true,计算图像梯度的时候会使用:(更加精确)
    这里写图片描述
  • 如果为false,计算图像梯度的时候会使用:
    这里写图片描述

这里实现第一个方法l2 范数:

import math
import cv2
import os
import numpy as np
path = os.path.join(os.getcwd(), 'pic/2.jpg')
img = cv2.imread(path, 1)
shape = img.shape
height = shape[0]
width = shape[1]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#彩色图变成灰度图
dst = np.zeros((height, width,1), np.uint8) #存放完成边缘检测的图片, 第二个参数 uint的范围0-255
#[1, 0 ,-1        [ 1, 2. 1 
# 2,0 -2                0, 0  0
# 1,0 -1]               -1 , -2 ,-1
# 竖直方向的边缘检测       水平方向上的
for i in range(0,height-2):#卷积计算
    for j in range(0,width-2):
        y = gray[i,j] + 2*gray[i,j+1] + gray[i, j+2]-gray[i+2, j] - 2*gray[i+2,j+1] -gray[i+2,j+2]
        x = gray[i,j] -gray[i,j+2] + 2*gray[i+1,j] - 2*gray[i+1,j+2] +gray[i+2,j]-gray[i+2,j+2]
        ddd= x *x + y*y
        grad = math.sqrt(ddd)
        print grad
        if grad>200:#门阀值
            dst[i, j]= 255

cv2.imshow('dd',dst)
cv2.waitKey(0)

b

猜你喜欢

转载自blog.csdn.net/qq_42105426/article/details/89486646