题目描述 利用opencv
或其他工具编写程序实现算子边缘检测。
实现过程
import cv2
import numpy as np
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
# 判断是否OpenCV图片类型
if (isinstance(img, np.ndarray)):
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# 创建一个可以在给定图像上绘图的对象
draw = ImageDraw.Draw(img)
# 字体的格式
fontStyle=ImageFont.truetype("font/simsun.ttc",textSize, encoding="utf-8")
# 绘制文本
draw.text((left, top), text, textColor, font=fontStyle)
# 转换回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
# 反色后的原图
path = Path(Path().cwd().parent, 'test.bmp')
src = cv2.imread(str(path), 0)
src1 = cv2.bitwise_not(src) # 图像反色
src2 = cv2ImgAddText(src1, "反色后的原图", 20, 20, (0, 0 , 255), 20)
cv2.imshow('src2', src2)
# sobel算子边缘检测
mask_x = cv2.Sobel(src1, cv2.CV_16S, 1, 0, ksize=3) # 计算x方向梯度
mask_y = cv2.Sobel(src1, cv2.CV_16S, 0, 1, ksize=3) # 计算y方向梯度
img_x = cv2.convertScaleAbs(mask_x) # 取绝对值
img_y = cv2.convertScaleAbs(mask_y) # 取绝对值
mask = cv2.addWeighted(img_x, 0.3, img_y, 0.3, 0) # 按权相加
src3 = cv2.bitwise_not(mask) # 图像反色
src4 = cv2ImgAddText(src3, "sobel算子边缘检测结果", 20, 20, (0, 0 , 255), 20)
cv2.imshow('sobel', src4)
# robert算子边缘检测
kernelx = np.array([[-1, 0], [0, 1]], dtype=int)
kernely = np.array([[0, -1], [1, 0]], dtype=int)
x = cv2.filter2D(src1, cv2.CV_16S, kernelx)
y = cv2.filter2D(src1, cv2.CV_16S, kernely)
absX = cv2.convertScaleAbs(x) # 转uint8
absY = cv2.convertScaleAbs(y) # 转uint8
Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
src5 = cv2.bitwise_not(Roberts) # 图像反色
src6 = cv2ImgAddText(src5, "robert算子边缘检测结果", 20, 20, (0, 0 , 255), 20)
cv2.imshow('robert', src6)
# Laplacian_gauss算子边缘检测
dst = cv2.Laplacian(src1, cv2.CV_16S, ksize=5)
Laplacian = cv2.convertScaleAbs(dst)
src7 = cv2.bitwise_not(Laplacian) # 图像反色
src8 = cv2ImgAddText(src7, "sobel算子边缘检测结果", 20, 20, (0, 0 , 255), 20)
cv2.imshow('Laplacian_gauss', src8)
cv2.waitKey()
cv2.destroyAllWindows()
运行结果 经反色后的原图: