How do I edit a masked image?

How do ı make the image I’ve masked smoother? I want to remove the little white pixels from the second picture, and I want to throw some of the masked places out of the picture, how can I do that?

import cv2
import numpy as np

img = cv2.imread("colors.jpg")
height,width = 720,720
img = cv2.resize(img,(width,height))

hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

lower_range = np.array([100,50,50])
upper_range = np.array([150,255,255])

mask = cv2.inRange(hsv, lower_range, upper_range)
#res = cv2.bitwise_and(img,img, mask=mask)

cv2.imshow("Image",img)
cv2.imshow("Mask",mask)
#cv2.imshow("res",res)

cv2.waitKey(0)
cv2.destroyAllWindows

My image

My result

Answer

Try using the closing and opening concept of computer vision. You need is erosion in your case to get rid of the tiny white dots.

There are two things that can controlled for the resultant outcome as per your requirement i.e. kernel size and iterations.

Here is the code is I could reproduce and provide a near solution.

import numpy as np

img = cv2.imread("colors.jpg")
height,width = 720,720
img = cv2.resize(img,(width,height))

hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

lower_range = np.array([100,50,50])
upper_range = np.array([150,255,255])
kernel = np.ones((5,5),np.uint8)
mask = cv2.inRange(hsv, lower_range, upper_range)
erosion = cv2.erode(mask,kernel,iterations = 1)
#res = cv2.bitwise_and(img,img, mask=mask)


cv2.imshow("Image",img)
cv2.imshow("Mask",erosion)
#cv2.imshow("res",res)

cv2.waitKey(0)
cv2.destroyAllWindows
import cv2
import numpy as np
​
img = cv2.imread("colors.jpg")
height,width = 720,720
img = cv2.resize(img,(width,height))
​
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
​
lower_range = np.array([100,50,50])
upper_range = np.array([150,255,255])
kernel = np.ones((5,5),np.uint8)
mask = cv2.inRange(hsv, lower_range, upper_range)
erosion = cv2.erode(mask,kernel,iterations = 1)
#res = cv2.bitwise_and(img,img, mask=mask)
​
​
cv2.imshow("Image",img)
cv2.imshow("Mask",erosion)
#cv2.imshow("res",res)
​
cv2.waitKey(0)
cv2.destroyAllWindows

Result:

resultant image