简体   繁体   中英

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

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)

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这个形象。 (Not entirely sure about the cut-off, but that's usually not an issue when inserting into an already made image.)

I decided to just make the text sit on top of a transparent overlay as seen below:

overlay_image = np.copy(image_in)
cv2.rectangle(img=overlay_image, pt1=(center[0] + 50, center[1] - 50), pt2=(center[0] + 350, center[1] + 50),
              color=[0, 0, 0], thickness=-1)
cv2.putText(img=overlay_image, text=traffic_light_state, org=(center[0] + 50, center[1] + 10),
            fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=1, color=[255, 255, 255], thickness=1)
cv2.addWeighted(src1=overlay_image, alpha=0.5, src2=image_in, beta=0.5, gamma=0, dst=image_in)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM