Adds text to an image using PIL or cv2.
(self, xy, text, txt_color=(255, 255, 255), anchor='top', box_style=False)
| 237 | self.draw.rectangle(xy, fill, outline, width) |
| 238 | |
| 239 | def text(self, xy, text, txt_color=(255, 255, 255), anchor='top', box_style=False): |
| 240 | """Adds text to an image using PIL or cv2.""" |
| 241 | if anchor == 'bottom': # start y from font bottom |
| 242 | w, h = self.font.getsize(text) # text width, height |
| 243 | xy[1] += 1 - h |
| 244 | if self.pil: |
| 245 | if box_style: |
| 246 | w, h = self.font.getsize(text) |
| 247 | self.draw.rectangle((xy[0], xy[1], xy[0] + w + 1, xy[1] + h + 1), fill=txt_color) |
| 248 | # Using `txt_color` for background and draw fg with white color |
| 249 | txt_color = (255, 255, 255) |
| 250 | if '\n' in text: |
| 251 | lines = text.split('\n') |
| 252 | _, h = self.font.getsize(text) |
| 253 | for line in lines: |
| 254 | self.draw.text(xy, line, fill=txt_color, font=self.font) |
| 255 | xy[1] += h |
| 256 | else: |
| 257 | self.draw.text(xy, text, fill=txt_color, font=self.font) |
| 258 | else: |
| 259 | if box_style: |
| 260 | w, h = cv2.getTextSize(text, 0, fontScale=self.sf, thickness=self.tf)[0] # text width, height |
| 261 | outside = xy[1] - h >= 3 |
| 262 | p2 = xy[0] + w, xy[1] - h - 3 if outside else xy[1] + h + 3 |
| 263 | cv2.rectangle(self.im, xy, p2, txt_color, -1, cv2.LINE_AA) # filled |
| 264 | # Using `txt_color` for background and draw fg with white color |
| 265 | txt_color = (255, 255, 255) |
| 266 | cv2.putText(self.im, text, xy, 0, self.sf, txt_color, thickness=self.tf, lineType=cv2.LINE_AA) |
| 267 | |
| 268 | def fromarray(self, im): |
| 269 | """Update self.im from a numpy array.""" |
no test coverage detected