边缘检测算子

一、题目描述

将图像进行反色显示

进行Sobel算子滤波再将其反色显示

进行Roberts算子滤波再将其反色显示

二、实现过程

代码:

import cv2

import numpy as np

from matplotlib import pyplot as plt

from PIL import Image, ImageDraw, ImageFont

plt.rcParams['font.family'] = ['sans-serif']

plt.rcParams['font.sans-serif'] = ['SimHei']

# 读取图像

src_s = cv2.imread("C:/Users/dell/Desktop/dip.bmp")

#反色

ret,src = cv2.threshold(src_s,80,255,cv2.THRESH_BINARY)

src = cv2.bitwise_not(src_s)

cv2.imshow('src',src)

#Sobel算子滤波

x=cv2.Sobel(src,cv2.CV_16S,0,1)#对x求一阶导

y=cv2.Sobel(src,cv2.CV_16S,0,1)#对y求一阶导

absx=cv2.convertScaleAbs(x)#计算绝对值,并将图像转换为8位图进行显示

absy=cv2.convertScaleAbs(y)

sobel=cv2.addWeighted(absx,0.5,absy,0.5,0)#将图像进行线性混合

#反色

ret,sobel2 = cv2.threshold(sobel,80,255,cv2.THRESH_BINARY)

sobel2 = cv2.bitwise_not(sobel)

cv2.imshow('sobel2',sobel2)

cv2.waitKey(0)

#robert算子滤波

lenna_img = cv2.cvtColor(src,cv2.COLOR_BGR2RGB)

#灰度化处理图像

grayImage = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

#Roberts算子

kernelx = np.array([[-1,0],[0,1]], dtype=int)

kernely = np.array([[0,-1],[1,0]], dtype=int)

x = cv2.filter2D(grayImage, cv2.CV_16S, kernelx)#filter2D实现边缘提取

y = cv2.filter2D(grayImage, cv2.CV_16S, kernely)

#转uint8

absX = cv2.convertScaleAbs(x)     

absY = cv2.convertScaleAbs(y)   

robert = cv2.addWeighted(absX,0.5,absY,0.5,0)

ret,robert2= cv2.threshold(robert,80,255,cv2.THRESH_BINARY)

robert2 = cv2.bitwise_not(robert)

cv2.imshow('robert2',robert2) 

cv2.waitKey(0)

 

三、运行结果

截图

 

  

四、问题及解决方法

error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

在读取桌面文件的时候一直报错:(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

路径错误,找到图片打开属性复制路径,后还是不对,后把“\”换为”/”即可运行

五、实验总结

本次实验不难,学到了Sobel,Roberts,明白了遇到问题需要思考到底是那个地方错误,在网上寻找之后筛选有用的解答就可以解决问题。

 

 posted on 2020-03-12 11:08  ❤sndd❤  阅读(216)  评论(0编辑  收藏  举报