Python 3.7 OpenCV empty masks even with correct color range

644 Views Asked by At

I have an image that has been converted to HSV format. My goal is to isolate the green and black regions of the image, such that I can compare the area of the green regions and the area of the black regions. I can easily 'isolate' the black region by using OpenCV's inRange function to create a mask that detects black using the lower bound [0,0,0] and upper bound [1,0,0], which gives me this. Great.

However, when I try to isolate the green region, I face an issue where the mask is just completely black. I have tried using the color ranges found by utilising this color picker, this OpenCV color picker script and Krita's color picker tool, all of which gave me differing ranges. For reference, I'll attach the ranges I have tried. From my understanding of the inRange function, the function spits out whatever output is within the lower and upper bounds that are present in the img file given, but I cannot for the life of me get it to work.

Some references I used include this StackOverflow answer, the OpenCV documentation page and this StackOverflow post.

Here is my code, which includes the color ranges I have used.

import cv2 as cv
import numpy as np

# Read image
img = cv.imread('contrast.png')
# Convert to HSV format
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
# Save file
cv.imwrite('hsv.png', hsv)
# cv.imshow('hsv', hsv)

# Using values from Color Picker from AlloyUI 
lower = np.array([100,210,210])
upper = np.array([145,255,255])
# Using OpenCV color picker script values
# lower = np.array([32,0,0])
# upper = np.array([89, 255, 255])
# Using Krita's color picker tool
# lower = np.array([36,25,25])
# upper = np.array([70,255,255])

# Create mask using lower and upper bounds
mask = cv.inRange(hsv, lower, upper)

cv.imwrite('mask.png', mask)
cv.imshow('mask', mask)
0

There are 0 best solutions below