Creating a Filter, Edge Detection

Import resources and display image

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

import cv2
import numpy as np

%matplotlib inline

# Read in the image
image = mpimg.imread('images/curved_lane.jpg')

plt.imshow(image)

Convert the image to grayscale

# Convert to grayscale for filtering
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

plt.imshow(gray, cmap='gray')
Creating a Filter, Edge Detection_第1张图片

TODO: Create a custom kernel

Below, you've been given one common type of edge detection filter: a Sobel operator.

The Sobel filter is very commonly used in edge detection and in finding patterns in intensity in an image. Applying a Sobel filter to an image is a way of taking (an approximation) of the derivative of the image in the x or y direction, separately. The operators look as follows.

# Create a custom kernel

# 3x3 array for edge detection
sobel_y = np.array([[ -1, -2, -1], 
                   [ 0, 0, 0], 
                   [ 1, 2, 1]])

## TODO: Create and apply a Sobel x operator


# Filter the image using filter2D, which has inputs: (grayscale image, bit-depth, kernel)  
filtered_image = cv2.filter2D(gray, -1, sobel_y)
#-1 指的是输出与输入类型一致
plt.imshow(filtered_image, cmap='gray')
Creating a Filter, Edge Detection_第2张图片

最后一步 也是计算机视觉相当实用的一步,就是将图像转换为二值图像,也就是说 将其转换成纯粹的黑白图像 强度最高的边缘就会十分显眼了
Create binary image

reteval ,binary_image = cv2.threshold(filtered_image,100,255,cv2.THRESH_BINARY)
plt.imshow(binary_image,cmap ='gray')

常见的噪声有噪点和模糊的细节,检测这类边缘时,高通过滤器会强化图像里的这些噪声,通常我们需要增加一步操作 才能确保噪声得不到强化。在像这样使用高通过滤器之前,我们要用低通过滤器来对图像进行模糊处理 以便降噪

你可能感兴趣的:(Creating a Filter, Edge Detection)