图像降噪python

1.opencv

步骤:

1)blur滤波去噪音

2)floodfill清除背景色

3)转为灰度图

4)开闭运算使图像光滑

5)转为2值图

2.代码

 
 
#-*- coding:utf-8 -*-
import cv2 import numpy as npimg = cv2.imread("F/test.jpg") #载入图像h, w = img.shape[:2] #获取图像的高和宽 cv2.imshow("Origin", img) #显示原始图像blured = cv2.blur(img,(5,5)) #进行滤波去掉噪声cv2.imshow("Blur", blured) #显示低通滤波后的图像mask = np.zeros((h+2, w+2), np.uint8) #掩码长和宽都比输入图像多两个像素点,满水填充不会超出掩码的非零边缘 #进行泛洪填充cv2.floodFill(blured, mask, (w-1,h-1), (255,255,255), (2,2,2),(3,3,3),8)cv2.imshow("floodfill", blured) #得到灰度图gray = cv2.cvtColor(blured,cv2.COLOR_BGR2GRAY) cv2.imshow("gray", gray) #定义结构元素 kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(50, 50))#开闭运算,先开运算去除背景噪声,再继续闭运算填充目标内的孔洞opened = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel) closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel) cv2.imshow("closed", closed) #求二值图ret, binary = cv2.threshold(closed,250,255,cv2.THRESH_BINARY) cv2.imshow("binary", binary) #找到轮廓_,contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #绘制轮廓cv2.drawContours(img,contours,-1,(0,0,255),3) #绘制结果cv2.imshow("result", img)cv2.waitKey(0) cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/qq_34568522/article/details/79881300