Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show white text on an image with black border using OpenCV2?

Tags:

python

opencv

I have the following line of code to put text on an image but it is not legible on most occasions. How can I make the text white but with a black border around the text?

cv2.putText(img=image_in, text=traffic_light_state, org=(center[0] + 50, center[1]),
            fontFace=cv2.FONT_HERSHEY_COMPLEX , fontScale=1, color=[255, 255, 255], lineType=cv2.CV_AA, thickness=2)
like image 230
uioporqwerty Avatar asked Jan 30 '18 07:01

uioporqwerty


1 Answers

The way I do it in my code is by drawing the same text twice. Once in the outline color with double thickness (adjust to your liking), and once in the text color afterwards.

cv2.putText(img=image_in, text=traffic_light_state, org=(center[0] + 50, center[1]),
        fontFace=cv2.FONT_HERSHEY_COMPLEX , fontScale=1, color=[0, 0, 0], lineType=cv2.LINE_AA, thickness=4)
cv2.putText(img=image_in, text=traffic_light_state, org=(center[0] + 50, center[1]),
        fontFace=cv2.FONT_HERSHEY_COMPLEX , fontScale=1, color=[255, 255, 255], lineType=cv2.LINE_AA, thickness=2)

In my experience, dilate, as recommended in comments, isn't the fastest. And addWeighted can be expensive if used in images as large as I frequently edit. There definitely are tricks to fix the speed in both instances, but this method is just easier.

size = cv2.getTextSize("Test", cv2.FONT_HERSHEY_COMPLEX, 2, 4)[0]
im = np.ones((size[1], size[0]), np.uint8)*127
cv2.putText(im, "Test", (0,size[1]), cv2.FONT_HERSHEY_COMPLEX, 2, (0,), 4)
cv2.putText(im, "Test", (0,size[1]), cv2.FONT_HERSHEY_COMPLEX, 2, (255,), 2)
cv2.imwrite("test.png", im)

yields this image. (Not entirely sure about the cut-off, but that's usually not an issue when inserting into an already made image.)

like image 93
Poik Avatar answered Sep 21 '22 04:09

Poik