OpenCV:用不一样的方法去除图像噪声小点

相较于传统方法我使用了两种不一样的方法来做到了对图像上的噪声小点清除

原图:在这里插入图片描述

传统方法

对于清除噪声小点无外乎就是图像平滑,高斯模糊,中值模糊,双边滤波。这一类方法在不会调参深入了解过的情况下,使用起来无疑是鸡肋。

轮廓描绘清除

通过对图像做一个轮廓描绘,把它描绘在新的白色画布上。与此同时,由于图像小点的面积单一且小,我们做一个if 判断,只把面积大于一定阈值的轮廓描绘在画布上。

import cv2
import numpy as np
img = cv2.imread('timg1.tiff')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(img, 127, 255, 0)
white = np.ones([737, 487, 3], np.uint8)*255    # 这里可以设定为图片的大小
conts, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(conts):
    # cv.drawContours(image, contours, i, (255, 0, 0), 0)
    # print(i)
    cnt = contour
    M = cv2.moments(cnt)
    # print(type(M['m00']))
    temp = 5.00
    if M['m00'] > temp:
        cv2.drawContours(white, conts, i, (0, 0, 255), 3)

cv2.imshow('white',white)
cv2.waitKey(0)
cv2.destroyWindow()

在这里插入图片描述

遍历图像的像素替代

通过把噪声小点判断是一个在九宫格正中心的孤岛,当我们检测到这个孤岛的时候就把它替换成白色。

from tkinter.filedialog import askopenfilename

import cv2
import numpy as np


def access_pixels(frame):
    white  = np.ones([737, 487, 3], np.uint8)*255
    print(frame.shape)  # shape内包含三个元素:按顺序为高、宽、通道数
    height = frame.shape[0]
    weight = frame.shape[1]
    channels = frame.shape[2]
    a = 1   # 高最小值
    b = height-1    # 高最大值
    c = 1   # 宽最小值
    d = weight-1    # 宽最大值
    
    print("weight : %s, height : %s, channel : %s" % (weight, height, channels))
    for row in range(height):  # 遍历高
        for col in range(weight):  # 遍历宽
            if a < row < b and c< col< d:   # 因为边界加减就会超出值,所以这里做一个阈值判断
                if HSV[row, col][2] != 255:
                    result = judge_point(row,col)
                    if result == True:
                        frame[row, col] = white[1, 1]   #替换成白色背景色,即清除噪声小点
                    
    cv2.imwrite('result.png', frame)
    cv2.imshow("fanxiang", frame)


def judge_point(row, col):  # 用于判断它是不是一个孤岛
        temp1 = HSV[row-1, col-1]
        temp2 = HSV[row, col-1]
        temp3 = HSV[row+1, col-1]
        temp4 = HSV[row-1, col]
        temp6 = HSV[row+1, col]
        temp7 = HSV[row-1, col+1]
        temp8 = HSV[row, col+1]
        temp9 = HSV[row+1, col+1]
        for i in range(1, 10):
            if temp1[2] and temp2[2] and temp3[2] and temp4[2] and temp6[2] and temp7[2] and temp8[2] and temp9[2] == 255:
                return True
            else:
                return False
            
            
image = askopenfilename(title='选择文件')
src = cv2.imread(image)
HSV = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
access_pixels(src)
cv2.waitKey(0)

在这里插入图片描述

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值