TheNotoruous0307
TheNotoruous0307

Reputation: 27

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?

Upvotes: 0

Views: 2189

Answers (1)

Ahx
Ahx

Reputation: 7985

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)

Upvotes: 1

Related Questions