You should listen @fmw42, as he suggested, you could perform color segmentation to get the binary mask. Then using binary mask, you can remove the background.
-
- Performing color-segmentation: As @fmw42 suggested, we convert the loaded image to the HSV format define lower/upper ranges and perform color segmentation using
cv2.inRange
to obtain a binary mask
-
- Extracting rod: After obtaining binary mask we will use it to remove the background and separate rod from the rest of the image using
cv2.bitwise_and
. Arithmetic operation and is highly useful for defining roi in hsv colored images.
Code:
import cv2
import numpy as np
# Load the image
img = cv2.imread("iSXsL.jpg")
# Convert to HSV color-space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Perform color-segmentation to get the binary mask
lwr = np.array([0, 0, 0])
upr = np.array([179, 255, 146])
msk = cv2.inRange(hsv, lwr, upr)
# Extracting the rod using binary-mask
krn = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 3))
dlt = cv2.dilate(msk, krn, iterations=5)
res = 255 - cv2.bitwise_and(dlt, msk)
# Display
cv2.imshow("res", res)
cv2.waitKey(0)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…