Search code examples
pythonrgbopencvhsv

How to ouput image containing only specified color range?


I only want the purple lane in the output image.

import cv2
import numpy as np

img = cv2.imread("minimap_example.png")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #hsv image

lower_purple = np.array([154,135,160])
upper_purple = np.array([167,90,235])

mask = cv2.inRange(hsv, lower_purple, upper_purple)

lane = cv2.bitwise_and(img, img, mask=mask)
cv2.imwrite("laneOnly.png", lane)

But the output image is not correct at all : enter image description here

How to resolve this error?


Solution

  • There is something wrong with the range.

    If you check (print) at your image, zooming into the lane to this slice hsv[40:60, 80:90], you'll find the values of the hsv color are around [136 167 243].

    So trying with those values gives a better result:

    lower_purple = (136,167,155)
    upper_purple = (136,167,243)
    

    So, dig deeper and find the better option for you.