Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

remove blue background color in Python OpenCV

enter image description here

the task is to remove the blue background in the picture, how can I implement that?

question from:https://stackoverflow.com/questions/66059653/remove-blue-background-color-in-python-opencv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

    1. 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
    1. 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.

  • Result will be:

    • enter image description here

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...