8邻域降噪(各种边缘去噪)
8邻域去噪
import cv2
def noise_remove_cv2(image_name, k):
    """
    8邻域降噪
    Args:
        image_name: 图片文件命名
        k: 判断阈值
    Returns:
    """
    def calculate_noise_count(img_obj, w, h):
        """
        计算邻域非白色的个数
        Args:
            img_obj: img obj
            w: width
            h: height
        Returns:
            count (int)
        """
        count = 0
        width, height = img_obj.shape
        for _w_ in [w - 1, w, w + 1]:
            for _h_ in [h - 1, h, h + 1]:
                if _w_ > width - 1:
                    continue
                if _h_ > height - 1:
                    continue
                if _w_ == w and _h_ == h:
                    continue
                if img_obj[_w_, _h_] < 230:  # 二值化的图片设置为255
                    count += 1
        return count
    img = cv2.imread(image_name, 1)
    # 灰度
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    w, h = gray_img.shape
    for _w in range(w):
        for _h in range(h):
            if _w == 0 or _h == 0:
                gray_img[_w, _h] = 255
                continue
            # 计算邻域pixel值小于255的个数
            pixel = gray_img[_w, _h]
            if pixel == 255:
                continue
            if calculate_noise_count(gray_img, _w, _h) < k:
                gray_img[_w, _h] = 255
    return gray_img
if __name__ == '__main__':
    image = noise_remove_cv2("./output/001.jpg", 2)
    # cv2.imshow('img', image)
    cv2.imwrite("./remove_noise_output/001.jpg", image)
边缘的白点
from PIL import Image
# 去除干扰线
im = Image.open('./output2/2.jpg')
# 图像二值化
data = im.getdata()
w, h = im.size
# black_point = 0
white_point = 0
for x in range(1, w - 1):
    for y in range(1, h - 1):
        mid_pixel = data[w * y + x]  # 中央像素点像素值
        if mid_pixel < 50:  # 找出上下左右四个方向像素点像素值
            top_pixel = data[w * (y - 1) + x]
            left_pixel = data[w * y + (x - 1)]
            down_pixel = data[w * (y + 1) + x]
            right_pixel = data[w * y + (x + 1)]
            # 判断上下左右的黑色像素点总个数
            if top_pixel > 240:
                white_point += 1
            if left_pixel > 240:
                white_point += 1
            if down_pixel > 240:
                white_point += 1
            if right_pixel > 240:
                white_point += 1
            if white_point < 1:
                im.putpixel((x, y), 0)
            # print(black_point)
            white_point = 0
im.save('xxxx.jpg')
边缘去掉
from PIL import Image
# 去除干扰线
im = Image.open('./output1/1.jpg')
# 图像二值化
data = im.getdata()
w, h = im.size
black_point = 0
for x in range(1, w - 1):
    for y in range(1, h - 1):
        if x < 10 or y < 10:
            im.putpixel((x - 1, y - 1), 0)
        if x > w - 3 or y > h - 3:
            im.putpixel((x + 1, y + 1), 0)
im.save('xxxxx.jpg')
    有什么问题可以加qq:1281372141进行交流

                
            
        
浙公网安备 33010602011771号