How can I remove small pixel clusters from a transparent png using python
Question:
I am trying to remove random pixel clusters noise from a transparent png using python.
I have used eroding and then dilating like this
import cv2
import numpy as np
img = cv2.imread('test1.png')
blurred_img = cv2.medianBlur(img, 1)
kernel = np.ones((2,2),np.uint8)
erosion = cv2.erode(blurred_img, kernel, iterations=1)
output = cv2.dilate(erosion, kernel, iterations=1)
cv2.imwrite('output.png', output)
but this blurs the image to the point where it loses a lot of details:
I have tried many alternatives but I just can’t obtain the result I want… The original image just without that random pixel noise around it. I hope someone can help me.
Answers:
area_opening from skimage can be used on the alpha channel. We use the cv2.IMREAD_UNCHANGED flag to get this channel and modify it.
the following code has an output
import cv2
import numpy as np
from skimage.morphology import area_opening
img = cv2.imread('test.png', cv2.IMREAD_UNCHANGED)
img[:,:,3][area_opening(img[:,:,3], 7) == 0] = 0
cv2.imwrite('output.png', img)
I am trying to remove random pixel clusters noise from a transparent png using python.
I have used eroding and then dilating like this
import cv2
import numpy as np
img = cv2.imread('test1.png')
blurred_img = cv2.medianBlur(img, 1)
kernel = np.ones((2,2),np.uint8)
erosion = cv2.erode(blurred_img, kernel, iterations=1)
output = cv2.dilate(erosion, kernel, iterations=1)
cv2.imwrite('output.png', output)
but this blurs the image to the point where it loses a lot of details:
I have tried many alternatives but I just can’t obtain the result I want… The original image just without that random pixel noise around it. I hope someone can help me.
area_opening from skimage can be used on the alpha channel. We use the cv2.IMREAD_UNCHANGED flag to get this channel and modify it.
the following code has an output
import cv2
import numpy as np
from skimage.morphology import area_opening
img = cv2.imread('test.png', cv2.IMREAD_UNCHANGED)
img[:,:,3][area_opening(img[:,:,3], 7) == 0] = 0
cv2.imwrite('output.png', img)