How to remove image noise using opencv - python?

2024/10/5 3:31:40

I am working with skin images, in recognition of skin blemishes, and due to the presence of noises, mainly by the presence of hairs, this work becomes more complicated.

I have an image example in which I work in an attempt to highlight only the skin spot, but due to the large number of hairs, the algorithm is not effective. With this, I would like you to help me develop an algorithm to remove or reduce the amount of hair so that I can only highlight my area of ​​interest (ROI), which are the spots.

Algorithm used to highlight skin blemishes:

import numpy as np
import cv2#Read the image and perform threshold
img = cv2.imread('IMD006.bmp')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray,5)
_,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)#Search for contours and select the biggest one
contours, hierarchy =         cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cnt = max(contours, key=cv2.contourArea)#Create a new mask for the result image
h, w = img.shape[:2]
mask = np.zeros((h, w), np.uint8)#Draw the contour on the new mask and perform the bitwise operation
cv2.drawContours(mask, [cnt],-1, 255, -1)
res = cv2.bitwise_and(img, img, mask=mask)#Display the result
cv2.imwrite('IMD006.png', res)
#cv2.imshow('img', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

Example image used: enter image description here

How to deal with these noises to the point of improving my region of interest?

Answer

This is quite a difficult task becasue the hair goes over your ROI (mole). I don't know how to help remove it from the mole but I can help to remove the backround like in the picture without hairs. For the removal of hairs from mole I advise you to search for "removing of watermarks from image" and "deep neural networks" to maybe train a model to remove the hairs (note that this task will be quite difficult).

That being said, for the removing of background you could try the same code that you allready have for detection without hairs. You will get a binary image like this:

enter image description here

Now your region is filled with white lines (hairs) that go over your contour that is your ROI and cv2.findContours() would also pick them out because they are connected. But if you look at the picture you will find out that the white lines are quite thin and you can remove it from the image by performing opening (cv2.morphologyEx) on the image. Opening is erosion followed by dilation so when you erode the image with a big enough kernel size the white lines will dissapear:

enter image description here

Now you have a white spot with some noises arround which you can connect by performing another dilation (cv2.dilate()):

enter image description here

To make the ROI a bit smoother you can blur the image cv2.blur():

enter image description here

After that you can make another treshold and search for the biggest contour. The final result:

enter image description here

Hope it helps a bit. Cheers!

Example code:

import numpy as np
import cv2# Read the image and perfrom an OTSU threshold
img = cv2.imread('hair.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)# Remove hair with opening
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)# Combine surrounding noise with ROI
kernel = np.ones((6,6),np.uint8)
dilate = cv2.dilate(opening,kernel,iterations=3)# Blur the image for smoother ROI
blur = cv2.blur(dilate,(15,15))# Perform another OTSU threshold and search for biggest contour
ret, thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cnt = max(contours, key=cv2.contourArea)# Create a new mask for the result image
h, w = img.shape[:2]
mask = np.zeros((h, w), np.uint8)# Draw the contour on the new mask and perform the bitwise operation
cv2.drawContours(mask, [cnt],-1, 255, -1)
res = cv2.bitwise_and(img, img, mask=mask)# Display the result
cv2.imshow('img', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
https://en.xdnf.cn/q/70535.html

Related Q&A

Django groups and permissions

I would like to create 2 groups (Professors, Students). And I would like to restrict students from creating and deleting Courses.views.py:def is_professor(function=None):def _is_professor(u):if user.gr…

How to (properly) use external credentials in an AWS Lambda function?

I have a (extremely basic but perfectly working) AWS lambda function written in Python that however has embedded credentials to connect to: 1) an external web service 2) a DynamoDB table. What the fu…

How to set environment variable TF_Keras = 1 for onnx conversion?

Recently updated to tensorflow 2.0 and am having trouble getting my .h5 models into .onnx . Used to be a very simple procedure but now I am having an issue. When I run the following code:# onnx testing…

Django App Engine: AttributeError: AnonymousUser object has no attribute backend

I am using djangoappengine. When I try create a new user, authenticate that user, and log them in, I get the following error AttributeError: AnonymousUser object has no attribute backend.My code is sim…

python identity dictionary [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate:How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError? I need…

Whats a good library to manipulate Apache2 config files? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

AttributeError: module object has no attribute webdriver

AttributeError: module object has no attribute webdriverwhy this error happen when write import selenium and when write code like this no error happenfrom selenium import webdriver

Mask Ocean or Land from data using Cartopy

I would like to mask the Land area from Sea Surface Temperature Data over the globe. I am using Cartopy to plot the data.import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs fr…

How to map func_closure entries to variable names?

I have a lambda object that is created in this function:def add_url_rule(self, rule, endpoint=None, view_func=None, **options):self.record(lambda s:s.add_url_rule(rule, endpoint, view_func, **options))…

How to use the convertScaleAbs() function in OpenCV?

I am trying to convert an image back to grayscale after applying Sobel filtering on it. I have the following code: import numpy as np import matplotlib.pyplot as plt import cv2image = cv2.imread("…