Why is the color range different between hsv and bgr when doing opencv color conversion?

43 Views Asked by At

I created a script to find a rectangle in a screenshot using a mask to detect the top of the said rectangle. I struggled a lot with color conversion because when converting the image from RGB to BGR, the mask worked perfectly. However, when converting the screenshot from RGB to HSV, the mask suddenly became empty.

Using some clunky manual screenshots while showing the HSV image with cv2.imshow(), I realized that the HSV value were pretty different that the ones I got when doing conversion using online converters. So at the moment, my script is working fine, but I don't understand where this gap in color values is coming. Here is a simplified version of the code I am using to do the detection, with some comments to explain the gaps in colors. :

import time
import platform
import cv2
import numpy as np
from PIL import ImageGrab


#blue_sky_color_upper = np.array([190//2, 33, 82])  # theoretical HSV value based off (210, 200, 140) BGR values which work when converting the image to BGR but not in HSV
#blue_sky_color_lower = np.array([180//2, 42, 75])  # theoretical HSV value based off (190, 190, 110) BGR values which work when converting the image to BGR but not in HSV
blue_sky_color_upper = np.array([95, 100, 210])  # working HSV value
blue_sky_color_lower = np.array([90, 80, 190])  # working HSV value

game_screenshot = ImageGrab.grab()
default_image_array = np.array(game_screenshot)

if game_screenshot.mode == "RGBA":  # converts the default color model to BGR
    cv2_array = cv2.cvtColor(default_image_array, cv2.COLOR_RGBA2BGR)
    cv2_array = cv2.cvtColor(cv2_array, cv2.COLOR_BGR2HSV)
else:
    cv2_array = cv2.cvtColor(default_image_array, cv2.COLOR_RGB2HSV)

image_capture_mask = cv2.inRange(cv2_array, blue_sky_color_lower, blue_sky_color_upper)
cv2.imshow("mask", image_capture_mask)
cv2.waitKey(0)
0

There are 0 best solutions below