Skip to content
Advertisement

Unable to generate contour on segmented image using OpenCV based on a specific color(cv2.inRange)

I have a segmented image, which is output of an AI model.The next step is to create contour and overlay on the original image(non segmented)using OpenCV around a specific color on the segmented image. enter image description here

I tried with the below code snippet.

img2 = cv2.imread('output.png')
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
lower_brown = np.array([50,50,80])
upper_brown = np.array([(50,50,80)])
mask_brown = cv2.inRange(img2, lower_brown, upper_brown)
contours, test = cv2.findContours(mask_brown, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

But unfortunately I am unable to generate mask and contour which returns empty array. Any leads would be appreciated

Advertisement

Answer

You approach is correct for Python/OpenCV. However, why did you convert from BGR to RGB. When you do that your subsequent colors would need to be reversed, since you specified them in the order of B,G,R.

The following works fine for me when I remove the conversion from BGR to RGB:

import cv2
import numpy as np
img2 = cv2.imread('segment.png')
lower_brown = np.array([50,50,80])
upper_brown = np.array([(50,50,80)])
mask_brown = cv2.inRange(img2, lower_brown, upper_brown)
cv2.imshow("mask_brown", mask_brown)
cv2.waitKey(0)
cv2.destroyAllWindows()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement