Search code examples
pythonmatplotlibimage-processingnoise-reduction

How to remove noise from image in python


I'm trying to remove noise from image, i'm trying to make white pixel if certain condition met but i'm struggling to make that happen.

This is my image and i want to remove all gray color lines only want high intensity color like blue red and green . Sorry for my editing

enter image description here

This is my code where i have tried to check the condition which succeed then i'll change the pixel to white

height, width = image.shape[0:2]
for i in range(0, height):  # looping at python speed...
    for j in range(0, width):
        # print(image)
        if ((image[i][j][1] * 255 == image[i][j][2] * 255 == image[i][j][3] * 255) or (
                (image[i][j][0] * 255 == image[i][j][1] * 255) and (
                image[i][j][3] * 255 >= 245))):
            # print(image[i][j][2] * 255)
            image[i][j] = 0

plt.imshow(image)
plt.savefig("filename.png")
plt.show()

Solution

  • I have tried with opacity and it work for me. Then i have use kernel. One issue with this answer is that it taking bit more time. Please let me know if their any better way

    import matplotlib.pyplot as plt
    import cv2
    import numpy as np
    
    image = plt.imread('../heatmapwms.png')
    
    height, width = image.shape[0:2]
    for i in range(0, height):  
        for j in range(0, width):
            if (image[i][j][3] <= .34 or (
                    (image[i][j][2] * 255 > 170) and (image[i][j][1] * 255 > 150) and (image[i][j][0] * 255 > 150))):
                image[i][j] = 0
    
    kernel = np.ones((3, 3), np.float32) / 9
    image = cv2.filter2D(image, -1, kernel)
    
    for i in range(0, height):  
        for j in range(0, width):
            if (image[i][j][3] <= .30 or (
                    (image[i][j][2] * 255 > 170) and (image[i][j][1] * 255 > 150) and (image[i][j][0] * 255 > 150))):
                image[i][j] = 0
    
    kernel = np.ones((3, 3), np.float32) / 9
    image = cv2.filter2D(image, -1, kernel)
    
    plt.imshow(image)
    plt.savefig("filename.png")
    plt.show()