Python OpenCV 实现图像滤波
一、实验过程
我使用的是python语言+openCV来实现图像滤波。
使用imread()函数读取图片,使用imshow()函数显示图片,waitKey()函数含义为按下任意键继续;
代码示例:
img = cv2.imread("photo1.bmp")cv2.imshow("img",img)cv2.waitKey(0)
结果:
我们可以用pil来实现在图片上显示文字,首先先安装pillow
实例代码:
#cv2和PIL中颜色的hex码的储存顺序不同,需转RGB模式 pil_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #Image.fromarray()将数组类型转成图片格式,与np.array()相反 pilimg = Image.fromarray(pil_img) draw = ImageDraw.Draw(pilimg)#PIL图片上打印汉字 font = ImageFont.truetype("simhei.ttf",50,encoding="utf-8") draw.text((0,0),"原图像",(255,0,0),font=font) img1 = cv2.cvtColor(np.array(pilimg),cv2.COLOR_RGB2BGR)#将图片转成cv2.imshow()可以显示的数组格式 cv2.imshow("img1",img1) cv2.waitKey()
结果:
均值滤波的实例代码:
img2 = cv2.blur(img,(5,5)) pil_img1 = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB) pilimg1 = Image.fromarray(pil_img1) draw = ImageDraw.Draw(pilimg1)#PIL图片上打印汉字 font = ImageFont.truetype("simhei.ttf",20,encoding="utf-8") draw.text((0,0),"均值滤波",(255,0,0),font=font) img3 = cv2.cvtColor(np.array(pilimg1),cv2.COLOR_RGB2BGR) cv2.imshow("img3",img3) cv2.waitKey()
结果:
中值滤波的实例代码:
img_median = cv2.medianBlur(img, 5) pil_img2 = cv2.cvtColor(img_median,cv2.COLOR_BGR2RGB) pilimg2 = Image.fromarray(pil_img2) draw = ImageDraw.Draw(pilimg2)#PIL图片上打印汉字 font = ImageFont.truetype("simhei.ttf",20,encoding="utf-8") draw.text((0,0),"中值滤波",(255,0,0),font=font) img4 = cv2.cvtColor(np.array(pilimg2),cv2.COLOR_RGB2BGR)#将图片转成cv2.imshow()可以显示的数组格式 cv2.imshow("img4",img4) cv2.waitKey(0)
结果:
高斯滤波的实例代码:
# 高斯滤波 img_Guassian = cv2.GaussianBlur(img,(5,5),0) pil_img3 = cv2.cvtColor(img_Guassian,cv2.COLOR_BGR2RGB) pilimg3 = Image.fromarray(pil_img3) draw = ImageDraw.Draw(pilimg3)#PIL图片上打印汉字 font = ImageFont.truetype("simhei.ttf",20,encoding="utf-8") draw.text((0,0),"高斯滤波",(255,0,0),font=font) img5 = cv2.cvtColor(np.array(pilimg3),cv2.COLOR_RGB2BGR)#将图片转成cv2.imshow()可以显示的数组格式 cv2.imshow("img5",img5) cv2.waitKey(0)
结果:
边缘检测的实例代码:
img6 = cv2.Canny(pil_img3,30,150) img_Guassian = cv2.GaussianBlur(img6,(5,5),0) pil_img4 = cv2.cvtColor(img6,cv2.COLOR_BGR2RGB) pilimg4 = Image.fromarray(pil_img4) draw = ImageDraw.Draw(pilimg4)#PIL图片上打印汉字 font = ImageFont.truetype("simhei.ttf",20,encoding="utf-8") draw.text((0,0),"高斯滤波边缘检测",(0,255,0),font=font) img7 = cv2.cvtColor(np.array(pilimg4),cv2.COLOR_RGB2BGR) cv2.imshow("img7",img7) cv2.waitKey(0)
结果:
二、实验中的错误
输入from PIL import Image,ImageDraw,ImageFont报错,然后发现自己没有安装pillow,则我们输入pip install pillow,在输入就成功了。
三、实验总结
学习了OpenCV的图像滤波,途中遇到了问题也较快解决,锻炼了自己的能力。
相关推荐
liangzuojiayi 2020-06-09
BeanJoy 2020-06-06
pythonxuexi 2020-05-10
wanff0 2020-05-04
Jasterwisdom 2019-06-27
xiaoseyihe 2017-11-23