Home > Blockchain >  Drawing Contours on Mask
Drawing Contours on Mask

Time:05-07

I have an image with a mask; I have found the contour of the object in the image. For some reason, when I call cv2.drawContours(), the contour of the object is drawn in grey. Is there any way to draw colored lines on the image?

Below is the code:

img = cv2.imread("Assets/Setup2.jpg")
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
masked_img = cv2.inRange(hsv_img, (50, 40, 40), (70, 255, 255))
contours = cv2.findContours(masked_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(masked_img, contours, -1, (60, 200, 200), 5)
cv2.imshow("Frame", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

CodePudding user response:

The contour is drawn in gray because the input image masked_img is a single-channel image. Output from cv2.threshold or cv2.inRange returns single-channel image regardless of its inputs.

Here is how you should fix your code to get the desired effects:

img = cv2.imread("Assets/Setup2.jpg")
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
masked_img = cv2.inRange(hsv_img, (50, 40, 40), (70, 255, 255))
masked_img = cv2.cvtColor(masked_img, cv2.COLOR_GRAY2BGR)  // changes gray to BGR
contours = cv2.findContours(masked_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(masked_img, contours, -1, (60, 200, 200), 5) 
cv2.imshow("Frame", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

or you can draw the contour directly on your input image. In which case you only need to change the cv2.drawContour to the following code

cv2.drawContours(img, contours, -1, (60, 200, 200), 5) 
  • Related