Reputation: 49
I am trying to draw a contour (https://docs.opencv.org/3.4.0/d4/d73/tutorial_py_contours_begin.html) with different colour on this image, however the contour always turns out to be white. Here is the following code
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Ron Shporer\Desktop\TESTSAVES\TESTLines.png',0)
ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)
cnt = contours[0]
cv2.drawContours(img, contours, -1, (255,0,0), 5)
cv2.namedWindow('img', cv2.WINDOW_NORMAL)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()`
the following picture:
Upvotes: 2
Views: 9378
Reputation: 173
try this
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Ron Shporer\Desktop\TESTSAVES\TESTLines.png',0)
img_color = cv2.imread(r'C:\Users\Ron Shporer\Desktop\TESTSAVES\TESTLines.png')
ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)
cnt = contours[0]
cv2.drawContours(img_color , contours, -1, (255,0,0), 5)
cv2.namedWindow('img_color ', cv2.WINDOW_NORMAL)
cv2.imshow('img_color ',img_color )
cv2.waitKey(0)
cv2.destroyAllWindows()
Upvotes: 1
Reputation: 1105
The solution is simple. You can convert the input image to the 3-channel image, then draw the contours on the converted color image.
Code would be something like this:
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Ron Shporer\Desktop\TESTSAVES\TESTLines.png',0)
ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)
cnt = contours[0]
result_img = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
cv2.drawContours(result_img, contours, -1, (255,0,0), 5)
cv2.namedWindow('img', cv2.WINDOW_NORMAL)
cv2.imshow('img', result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Upvotes: 4