Home > Back-end >  I want to remove the black noise at the border of the image
I want to remove the black noise at the border of the image

Time:08-28

I am looking for a way to remove the black dots around the image border using OpenCV.

Image:

enter image description here

Expected solution:

enter image description here

import cv2 

def get_img(img_name):
    lower = (0, 0, 0)
    upper = (75, 75, 75) 
    img = cv2.imread(img_name)
    #print(img)
    img_rgb_inrange = cv2.inRange(img, lower, upper)
    neg_rgb_image = ~img_rgb_inrange
    w = cv2.cvtColor(neg_rgb_image,cv2.COLOR_GRAY2RGB)
    image3 = img-w
    cv2.imwrite('img.png', image3) 

get_img('address of the img')

I used the above code that I saw in enter image description here

Final Output:

enter image description here

Wondering, is there any dynamic way (instead of initializing upper and lower bounds) where I can remove the noise from the image but still maintain my foreground and background?

CodePudding user response:

import cv2
import matplotlib.pyplot as plt

image = cv2.imread('E3BbU.jpeg')
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)
image2 = image.copy()
cv2.drawContours(image=image2, contours=sorted(contours, key=len)[:-1], contourIdx=-1, color=(255, 255, 255), thickness=2, lineType=cv2.LINE_AA)

fig, ax = plt.subplots(2, 1)
for i, img in enumerate([image, image2]):
    ax[i].imshow(img);
    ax[i].axes.get_xaxis().set_visible(False)
    ax[i].axes.get_yaxis().set_visible(False)
plt.show()

enter image description here

  • Related